Consider this code, that tries to call the base class comparison operator from the derived class operator:
struct Base
{
protected:
int _a;
bool operator == ( const Base& other ) const
{
return (_a == other._a);
}
};
struct Derived : public Base
{
bool operator == ( const Derived& other ) const
{
return static_cast<Base>(*this) == static_cast<Base>(other);
}
};
int main()
{
Derived b1, b2;
if( b1 == b2 )
;
}
This fails with:
main.cpp:25:61: error: 'bool Base::operator==(const Base&)' is protected within this context return static_cast(*this) == static_cast(other);
I can't understand why I cannot access this operator from derived class.
I did some searching before asking and found this other question that looks similar. However:
- In the other question, the OP wants to compare in (the derived class) with a base class object, when I need a comparison of same type objects.
- I don't understand the given explanation.
- The case is somehow a bit different: in the other question, the accepted answer suggest doing the comparison of base members in the derived class. What if I have to do the comparison in base class ?
On point 2, let me elaborate: The accepted answer by @Barry suggest that as the object is converted to the base class... so it cannot access members of the base class! Why is that ? This is unclear to me.
Could someone give a clear explanation of the situation here (and possibly come with a solution...) ?
If you feel there might be some other question somewhere that clarifies this situation, please link to it (I could'nt find).