virtual function in private or protected inheritance

前端 未结 5 2224
予麋鹿
予麋鹿 2021-02-12 22:52

It\'s easy to understand the virtual function in public inheritance. So what\'s the point for virtual function in private or protected inheritance?

For example:

5条回答
  •  一个人的身影
    2021-02-12 23:16

    Your f() method is still overridden. This relationship is useful when implementing the Template Method design pattern. Basically, you'd implement common sets of operations in the base class. Those base class operations would then invoke a virtual method, like your f(). If the derived class overrides f(), the base class operations end up calling the derived version of f(). This allows derived classes to keep the base algorithm the same but alter the behavior to suit their needs. Here's a trivial example:

    #include 
    
    using namespace std;
    
    class Base
    {
    public:
      virtual void f() { cout<<"Base::f()" << endl; }
    protected:
      void base_foo() { f(); }
    };
    
    class DerivedOne: private Base
    {
    public: 
      void f() { cout << "Derived::f()" << endl;}
      void foo() { base_foo(); }
    };
    
    class DerivedTwo: private Base
    {
    public: 
      void foo() { base_foo(); }
    };
    
    int main()
    {
      DerivedOne d1;
      d1.foo();
    
      DerivedTwo d2;
      d2.foo();
    }
    

    Here's the result at run-time:

    $ ./a.out 
    Derived::f()
    Base::f()
    

    Both derived classes call the same base class operation but the behavior is different for each derived class.

提交回复
热议问题