Why redefinition under private inheritance?

class Base { public: virtual void f() {} }; class Derived : private Base { public: void f() override {} }; 

My question is, can this override be used? Private inheritance implies that you cannot store Derived in a Base pointer, and therefore you never need to dynamically send f to the correct type.

+7
c ++ c ++ 11
source share
1 answer

Just one example: the Derived::f1() function can call (public or protected) the Base::f2() functions, which in turn can call f() . In this case, dynamic sending is required.

Here is a sample code:

 #include "iostream" using namespace std; class Base { public: virtual void f() { cout << "Base::f() called.\n"; } void f2() { f(); // Here, a dynamic dispatch is done! } }; class Derived:private Base { public: void f() override { cout << "Derived::f() called.\n"; } void f1() { Base::f2(); } }; int main() { Derived D; D.f1(); Base B; B.f2(); } 

Output:

 Derived::f() called Base::f() called 
+7
source share

All Articles