Cannot access protected member of base class in derived class

后端 未结 4 773
渐次进展
渐次进展 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:29

    All the compilers that I tested complained about several things, and specifically the protected constructor would be a problem even if the assignment statement were removed.

    You don't get to access the protected members of any instance of a type you derive from. This issue is clarified in the examples of 11.4p1.

    class B {
    protected:
      int i;
      static int j;
    };
    
    class D1 : public B {
    };
    
    class D2 : public B {
      void mem(B*, D1*);
    };
    
    void D2::mem(B* pb, D1* p1) {
      pb->i = 1; // ill-formed
      p1->i = 2; // ill-formed
      // ...
    }
    

提交回复
热议问题