+ 6

operator overrriding

I have a class A that overload [] operator and class B inherited from A B have different behaviour with this operator ptotype in A int& operator[](int index); in B that U want const int operator[](int index); how to do this overload and avoiding override 2) can I make a member in A that is accessible outside except subclasses ? thanks for helping

9th Aug 2019, 10:34 PM
ABADA S
ABADA S - avatar
7 Antworten
+ 3
ok I will put my well then share if I felt I appreciate your aid
12th Aug 2019, 9:07 AM
ABADA S
ABADA S - avatar
+ 2
ABADA S , i actually don't get your requirement. please check below code and let me know if you are looking for some different behaviour : #include <iostream> using namespace std; class A { int array[5]; public : A() { array [0] = 1; array [1] = 2; array [2] = 3; array [3] = 4; array [4] = 5; } int& operator[](int index); }; class B : public A { int array[5]; public : B() { array [0] = 11; array [1] = 12; array [2] = 13; array [3] = 14; array [4] = 15; } const int operator[] (int index ); }; int& A::operator[](int index) { return array[index]; } const int B::operator[](int index) { return array[index]; } int main() { A obja; B objb; int x = obja[2]; int y = objb[2]; cout << x << endl; cout << y << endl; return 0; }
10th Aug 2019, 6:07 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
Ketan Lalcheta in this code why did you declared and define outside ? can you do it but define inside the classes? (your way is working thanks for it) for the second question I know something about it and how does it work , please give me an example 😊
11th Aug 2019, 8:28 PM
ABADA S
ABADA S - avatar
+ 2
I got a compile error when defining inside ... maybe I have problems in compiler
12th Aug 2019, 8:33 AM
ABADA S
ABADA S - avatar
+ 1
for your second question, you can have keyword friend... let me know if you need more details or example on friend class nd friend function
10th Aug 2019, 6:09 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
ABADA S you can define inside class as well.. I generally declare class in header file and define it into source cpp files so I did it same way in a single file.. refer below code for friend function: https://code.sololearn.com/cJVcu6dzm5fU/?ref=app
12th Aug 2019, 8:24 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
try it on sololearn and share code link if you get error...
12th Aug 2019, 8:48 AM
Ketan Lalcheta
Ketan Lalcheta - avatar