mkmostafa mkmostafa - 3 months ago 16
C++ Question

why override under private inheritance?

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

class Derived : private Base {
public:
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.

Answer

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 {
  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
Comments