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.
The private inheritance allows access to the protected members of the base class. The private inheritance allows Car to override Engine's virtual functions.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With