How to access protected method in base class from derived class?

后端 未结 6 504
孤街浪徒
孤街浪徒 2020-12-17 22:18

Here is a sample of code that annoys me:

class Base {
  protected:
    virtual void foo() = 0;
};

class Derived : public Base {
  private:
    Base *b; /* I         


        
6条回答
  •  抹茶落季
    2020-12-17 22:58

    Protected members in a base-class are only accessible by the current object.
    Thus, you are allowed to call this->foo(), but you are not allowed to call this->b->foo(). This is independent of whether Derived provides an implementation for foo or not.

    The reason behind this restriction is that it would otherwise be very easy to circumvent protected access. You just create a class like Derived, and suddenly you also have access to parts of other classes (like OtherDerived) that were supposed to be inaccessible to outsiders.

提交回复
热议问题