Accessing protected members in a derived class

前端 未结 8 2028
礼貌的吻别
礼貌的吻别 2020-11-22 11:30

I ran into an error yesterday and, while it\'s easy to get around, I wanted to make sure that I\'m understanding C++ right.

I have a base class with a protected memb

相关标签:
8条回答
  • 2020-11-22 12:20

    A class can only access protected members of instances of this class or a derived class. It cannot access protected members of instances of a parent class or cousin class.

    In your case, the Derived class can only access the b protected member of Derived instances, not that of Base instances.

    Changing the constructor to take a Derived instance will solve the problem.

    0 讨论(0)
  • 2020-11-22 12:22

    As mentioned, it's just the way the language works.

    Another solution is to exploit the inheritance and pass to the parent method:

    class Derived : public Base
    {
      protected:
        int d;
      public:
        void DoSomething(const Base& that)
        {
          Base::DoSomething(that);
          d=0;
        }
    };
    
    0 讨论(0)
提交回复
热议问题