Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Why override under private inheritance?




class Base {
   virtual void f() {}

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

My question is there any use to such override? Private inheritance implies that you can not store Derived in Base pointer and thus it will never be needed to dynamically dispatch f to the correct type.

like image 352
mkmostafa Avatar asked Aug 19 '16 08:08


People also ask

What is the point of private inheritance?

The private inheritance allows access to the protected members of the base class. The private inheritance allows Car to override Engine's virtual functions.

What happens when a class is inherited privately?

o When a base class is privately inherited by the derived class, public members of the base class becomes the private members of the derived class and therefore, the public members of the base class can only be accessed by the member functions of the derived class.

What happens when a protected member is inherited in private mode?

In private mode, the protected and public members of super class become private members of derived class. In this type of inheritance one derived class inherits from only one base class. It is the simplest form of Inheritance.

Can private data members be inherited?

The private members of a class can be inherited but cannot be accessed directly by its derived classes. They can be accessed using public or protected methods of the base class. The inheritance mode specifies how the protected and public data members are accessible by the derived classes.

1 Answers

Just one example: A function of Derived::f1() can call a (public or protected) functions of Base::f2(), which in turn can call f(). In this case, dynamic dispatch is needed.

Here is an example code:

#include "iostream"
using namespace std;

class Base {
    virtual void f()  { 
      cout << "Base::f() called.\n"; 
    void f2() { 
      f(); // Here, a dynamic dispatch is done!

class Derived:private Base {
    void f() override { 
      cout << "Derived::f() called.\n"; 
    void f1() { 

int main() {
  Derived D;
  Base    B;


Derived::f() called
Base::f() called
like image 83
ralfg Avatar answered Sep 21 '22 03:09