I have the following classes:
class Base {
protected:
int myint;
};
class Derived : public Base {
public:
bool operator==(Base &obj) {
if(myint == obj.myint)
return true;
else
return false;
}
};
But when I compile it, it gives the following errors:
int Base::myintis protected within this context
I thought that protected variables are accessible from the derived class under a public inheritance. What is causing this error?
Derived can access protected members of Base on all instances of Derived only. But obj isn't an instance of Derived, it's an instance of Base - so access is forbidden. The following would compile fine, since now obj is a Derived
class Derived : public Base {
public:
bool operator==(const Derived& obj) const {
return myint == obj.myint;
}
};
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