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?
The meaning of
protectedis 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 modifyb‘s member which is outside of your control (i.e. you can setthis->a, but notb.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
Athat takes anA*as argument (this constructor should be public) and then initialize it in the initializer list ofB:*
protectedgrants you access to the base member in any instance of your own type or derived from your own type.