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).
You can use both a structure and a class as base classes in the base list of a derived class declaration: If the derived class is declared with the keyword class , the default access specifier in its base list specifiers is private .
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.
Inheritance enables you to create new classes that reuse, extend, and modify the behavior defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class.
Is it possible for base class pointers to call methods declared in the derived class only? No, you can only call methods that are part of the class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With