Why can't my object access protected members of another object defined in common base class?

后端 未结 3 694
鱼传尺愫
鱼传尺愫 2020-12-06 19:00

The following code produces a compiler error:

\'BaseTest::_protMember\' : cannot access protected member declared in class \'BaseTest\'

3条回答
  •  無奈伤痛
    2020-12-06 19:08

    You can access protected members only in the class instance. That is :

    class SubTest : public BaseTest
    {
        SubTest(const BaseTest &baseTest)
        {
            _protMember = baseTest._protMember;
         // ^^^^^^^^^^^ Is good because you are in the instance of its class
            _protMember = baseTest._protMember;
         //               ^^^^^^^^^^^^^^^^^^^^^ Produce error because you are not in the baseTest instance.              
        };
    
        // followup question
        SubTest(const SubTest &subTest)
        {
            _protMember = subTest._protMember;
          // Compile because access modifiers work on class level, and not on object level.
        };
    };
    

    EDIT for the followup :

    The access modifiers work on class level, and not on object level.

    That is, two objects of the same class can access each others private members.

    This is my source : Why can I access private variables in the copy constructor?

提交回复
热议问题