class A{
public:
virtual char &operator[](int);
protected:
..
};
class B:A{
public:
A* &operator[](int);
protected:
}
Can I change the return type when I overload an overload of an operator?
thanks!
//EDIT
Okay, so now that we established that this wont work how can I build a work around?
Lets say I have classes A,B,C, and D.
class A{
public:
private:
char &operator[](int);
protected:
..
};
class B:A{
public:
virtual char &operator[](int);
};
class C: A{
public:
private:
A::&operator[](int);
}
class D: A{
public:
private:
A::&operator[](int);
}
Can I do something like this? If so is this the correct syntax?
The reason that a polymorphic function can’t return different types in different classes isn’t because someone on the C++ committee decided that it was “taboo”, but because any code that used that function’s return value couldn’t compile.
By creating an inheritance heirarchy, you’re able to access derived objects through a base pointer or reference:
Note that on the last line, the compiler won’t know what type of object
ais pointing to, since that’s determined at runtime. This is fine, because no matter what type of objectais pointing to,operator[]is still going to return a character. But what if that operator were allowed to return a different type in classB?Obviously, that last line makes no sense when
ais an object of typeB. In that case, you’re trying to assign aSequenceto a character. Likewise,Sequence c = (*a)[0];wouldn’t make sense ifawere an object of typeA.