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:
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.