subtle C++ inheritance error with protected fields

后端 未结 6 925
無奈伤痛
無奈伤痛 2020-12-03 02:38

Below is a subtle example of accessing an instance\'s protected field x. B is a subclass of A so any variable of type B is also of type A. Why can B::foo() access b\'s x fie

6条回答
  •  既然无缘
    2020-12-03 03:03

    In Public Inheritance:
    All Public members of the Base Class become Public Members of the derived class &
    All Protected members of the Base Class become Protected Members of the Derived Class.

    As per the above rule:
    protected member x from A becomes protected member of class B.

    class B can access its own protected members in its member function foo but it can only access members of A through which it was derived not all A classes.

    In this case, class B contains a A pointer a, It cannot access the protected members of this contained class.

    Why can the B::foo() access the members of the contained class B pointer b?

    The rule is:
    In C++ access control works on per-class basis, not on per-object basis.
    So an instance of class B will always have access to all the members of another instance of class B.

    An Code Sample, which demonstrates the rule:

    #include
    
    class MyClass 
    {
        public: 
           MyClass (const std::string& data) : mData(data) 
           {
           }
    
           const std::string& getData(const MyClass &instance) const 
           {
              return instance.mData;
           }
    
        private:
          std::string mData;
    };
    
    int main() {
      MyClass a("Stack");
      MyClass b("Overflow");
    
      std::cout << "b via a = " << a.getData(b) << std::endl;
      return 0;
    }
    

提交回复
热议问题