What Is Private Inheritance?

After private inheritance, all members of the base class are private members in the derived class.

Private inheritance

Right!
After private inheritance,
After private inheritance, all members of the base class are private members in the derived class. It doesn't seem to make any sense, but private inheritance can help us reuse base class code and prevent exposure of the base class interface.
Consider the following example:
#include <iostream>
using std :: cout;
using std :: endl;
class engine {
public:
void start () {cout << "engine-> start" << endl;}
void move () {cout << "engine-> move" << endl;}
void stop () {cout << "engine-> stop" << endl;}
};
class wheel {
public:
void start () {cout << "wheel-> start" << endl;}
void move () {cout << "wheel-> move" << endl;}
void stop () {cout << "wheel-> stop" << endl;}
};
class car: private engine, private wheel {
public:
void start ();
void move ();
void stop ();
};
void car :: start () {
engine :: start ();
wheel :: start ();
}
void car :: move () {
engine :: move ();
wheel :: move ();
}
void car :: stop () {
engine :: stop ();
wheel :: stop ();
}
int main (int argc, char * argv []) {
car ca;
ca.start ();
ca.move ();
ca.stop ();
return 0;
}
In the example, the class car is privately inherited from the class engine and class wheel. The three member functions of class car, start (), move (), and stop (), are implemented by calling the member functions of class engine and wheel respectively. The advantage of this is that it does not Need to rewrite and use the functions inherited from the base class directly. At the same time, because it is private inheritance, the objects that can pass the car class can not directly call the functions of the engine and wheel classes to prevent the exposure of unnecessary functions. Users do not need to care about the specific implementation of start (), move (), stop (), nor do they need to control the actions of engine and wheel.

IN OTHER LANGUAGES

Was this article helpful? Thanks for the feedback Thanks for the feedback

How can we help? How can we help?