Protected data in parent class not available in child class?

前端 未结 4 822
暖寄归人
暖寄归人 2020-12-03 17:37

I am confused: I thought protected data was read/writable by the children of a given class in C++.

The below snippet fails to compile in MS Compiler

         


        
4条回答
  •  醉话见心
    2020-12-03 18:34

    The constructor of B is private. If you do not specify anything, in a class, the default modifier is private (for structs it is public). So in this example the problem is that you cannot construct B. When you add public to constructor B anoter problem arises:

    B has the right to modify the part of A it derives from but not another A like in this case.

    You could do following:

    class A
    {
    public:
      A()
          : data(0)
      {
      }
      A(A &a)
      {
        data = a.data;
      }
    protected:
      int data;
    };
    
    class B : public A
    {
    public:
      B(A &a)
          : A(a)
      {
      }
    };
    
    int main()
    {
      A a;
      B b = a;
      return 0;
    }
    

提交回复
热议问题