Cannot access protected member of base class in derived class

后端 未结 4 761
渐次进展
渐次进展 2021-01-07 19:01

I have the following code:

struct A {
protected:
    A() {}

    A* a;
};

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

    A b;
};

4条回答
  •  没有蜡笔的小新
    2021-01-07 19:07

    There are actually two separate problems here.

    The first is that the line doesn't just do an assignment, but tries to initialize the base class (which works fine) and the member b. To create the b member it needs to construct it, and as a member it needs public access to a constructor, which it doesn't have.

    Then the assignment also is unable to access non-public member of b because again, it's not of type B but type A instead.

    Remember that protected means you can access parts of A through a B object (or child) only.

    In this case tell us your real problem and we can try to help solve it. Inheriting and composing from the same type is a design smell.

提交回复
热议问题