I have abstract class A, from which I inherit a number of classes. In the derived classes I am trying to access protected function in A trough A pointer. But I get a compiler error.
class A
{
protected:
virtual void f()=0;
};
class D : public A
{
public:
D(A* aa) :mAPtr(aa){}
void g();
protected:
virtual void f();
private:
A* mAPtr; // ptr shows to some derived class instance
};
void D::f(){ }
void D::g()
{
mAPtr->f();
}
The compiler error says : cannot access protected member A::f declared in class A.
If I declare mAPtr to be D*, instead A* everything compiles. And I don’t understand why is this.
Relying on
privateaccess works on unrelated instances of the same type.Relying on
protectedaccess works on unrelated instances of the same type (and of more derived types).However, relying on
protectedaccess does not work on unrelated instances of a base type.So
Dor something derived fromD, but notA.It’s an oft-questioned cute oddity about C++ that nonetheless is designed to try to avoid pitfalls. After all, you don’t know what type
*mAPtrreally has.