+ 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
7 Antworten
+ 3
ok I will put my well then share if I felt
I appreciate your aid
+ 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;
}
+ 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 😊
+ 2
I got a compile error when defining inside ... maybe I have problems in compiler
+ 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
+ 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
+ 1
try it on sololearn and share code link if you get error...