Reputation: 6707
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:
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).
Upvotes: 5
Views: 2207
Reputation: 438
11.5 Protected member access [class.protected]
When a friend or a member function of a derived class references a protected nonstatic member function or protected nonstatic data member of a base class, an access check applies in addition to those described earlier in clause 11.102) Except when forming a pointer to member (5.3.1), the access must be through a pointer to, reference to, or object of the derived class itself (or any class derived from that class) (5.2.5). If the access is to form a pointer to member, the nested-name-specifier shall name the derived class (or any class derived from that class).
Upvotes: 3
Reputation: 15446
Instead of trying to do the static casts yourself to try and get the compiler to resolve to call the Base operator, you can just explicitly call the Base comparison operator.
In addition, since this won't be modifying the object, you should probably make this method (and the base method) const
.
Altogether that'd look like:
bool operator == ( const Derived& other ) const
{
return Base::operator==(other);
}
See it run here: ideone
Upvotes: 8