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

后端 未结 6 508
孤街浪徒
孤街浪徒 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 23:12

    One solution would be to declare a static protected function in Base that redirects the call to the private / protected function (foo in the example).

    Lets say:

    class Base {
    protected:
        static void call_foo(Base* base) { base->foo(); }
    private:
        virtual void foo() = 0;
    };
    
    class Derived : public Base {
    private:
        Base* b;
    protected:
        virtual void foo(){/* Some implementation */};
        virtual void foo2()
        {
            // b->foo(); // doesn't work
            call_foo(b); // works
        }
    };
    

    This way, we don't break encapsulation because the designer of Base can make an explicit choice to allow all derived classes to call foo on each other, while avoiding to put foo into the public interface or explicitly turning all possible subclasses of Base into friends.

    Also, this method works regardless of whether foo is virtual or not, or whether it is private or protected.

    Here is a link to a running version of the code above and here another version of the same idea with a little more business logic.

提交回复
热议问题