Protected data in parent class not available in child class?

前端 未结 4 823
暖寄归人
暖寄归人 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:31

    According to TC++PL, pg 404:

    A derived class can access a base class’ protected members only for objects of its own type.... This prevents subtle errors that would otherwise occur when one derived class corrupts data belonging to other derived classes.

    Of course, here's an easy way to fix this for your case:

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

提交回复
热议问题