|
|||||||||||||
|
Section 24:
|
[24.2] How are "private inheritance" and "composition" similar?
private inheritance is a syntactic variant of composition (AKA aggregation and/or has-a). E.g., the "Car has-a Engine" relationship can be expressed using simple composition:
class Engine {
public:
Engine(int numCylinders);
void start(); // Starts this Engine
};
class Car {
public:
Car() : e_(8) { } // Initializes this Car with 8 cylinders
void start() { e_.start(); } // Start this Car by starting its Engine
private:
Engine e_; // Car has-a Engine
};
The "Car has-a Engine" relationship can also be expressed using
private inheritance:
class Car : private Engine { // Car has-a Engine
public:
Car() : Engine(8) { } // Initializes this Car with 8 cylinders
using Engine::start; // Start this Car by starting its Engine
};
There are several similarities between these two variants:
There are also several distinctions:
Note that private inheritance is usually used to gain access into the protected members of the base class, but this is usually a short-term solution (translation: a band-aid). |
||||||||||||