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

eddie
  • 1,252
  • 3
  • 15
  • 20
mkmostafa
  • 3,071
  • 2
  • 18
  • 47

1 Answers1

7

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
ralfg
  • 552
  • 2
  • 11