class A {
public:
A() {auto tmp = &A::foo;}
protected:
void foo() {}
};
class B : public A {
public:
B() {auto tmp = &A::foo;}
};
Class A
compiles no problem. Class B
yields a compilation error:
'A::foo' : cannot access protected member declared in class 'A'
Why is that, what's the rationale? Is there a way to circumvent this (if I need that pointer for a callback, std::function
etc.)?
Only the member functions or the friend functions are allowed to access the private data members of a class.
Yes, the protected method of a superclass can be overridden by a subclass. If the superclass method is protected, the subclass overridden method can have protected or public (but not default or private) which means the subclass overridden method can not have a weaker access specifier.
The protected access modifier is accessible within the package. However, it can also accessible outside the package but through inheritance only. We can't assign protected to outer class and interface. If you make any constructor protected, you cannot create the instance of that class from outside the package.
Why is that, what's the rationale?
In general, a derived class can only access protected members of the same derived class, not of the base class itself or arbitrary classes with the same base class. So B
can access protected members of A
via B
, but not directly via A
.
Is there a way to circumvent this?
The inherited member is also a member of B
, and can be accessed as such:
auto tmp = &B::foo;
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