Search code examples
c++protectedaccess-control

Cannot access protected member of base class in derived class


I have the following code:

struct A {
protected:
    A() {}

    A* a;
};

struct B : A {
protected:
    B() { b.a = &b; }

    A b;
};

It strangely doesn't compile. The culprit is the b.a = &b; assignment: both GCC and clang complain that A() is protected, which shouldn't be a problem because B inherits A. Which dark corner of the standard have I come into?


Solution

  • The meaning of protected is that the derived type will have access to that member of its own base and not of any random object*. In your case, you care trying to modify b's member which is outside of your control (i.e. you can set this->a, but not b.a)

    There is a hack to get this to work if you are interested, but a better solution would be to refactor the code and not depend on hacks. You could, for example, provide a constructor in A that takes an A* as argument (this constructor should be public) and then initialize it in the initializer list of B:

    A::A( A* p ) : a(p) {}
    B::B() : b(&b) {}
    

    * protected grants you access to the base member in any instance of your own type or derived from your own type.