Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Here is a sample of code that annoys me:

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

class Derived : public Base {
  private:
    Base *b; /* Initialized by constructor, not shown here
                Intended to store a pointer on an instance of any derived class of Base */

  protected:
    virtual void foo() { /* Some implementation */ };
    virtual void foo2() {
      this->b->foo(); /* Compilator sets an error: 'virtual void Base::foo() is protected' */
    }
};

How do you access to the protected overrided function?

Thanks for your help. :o)

like image 570
Bernard Rosset Avatar asked Jan 12 '11 18:01

Bernard Rosset


2 Answers

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.

like image 83
Bart van Ingen Schenau Avatar answered Oct 23 '22 11:10

Bart van Ingen Schenau


Normally, you would do it using Base::foo(), which refers to the base class of the current instance.

However, if your code needs to do it the way you're trying to and it's not allowed, then you'll need to either make foo() public or make Derived a friend of Base.

like image 45
Jonathan Wood Avatar answered Oct 23 '22 12:10

Jonathan Wood