E.g., the "car has-a engine" relationship can be expressed using 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_;
};
The same "has-a" relationship can also be expressed using private
inheritance:
class Car : private Engine {
public:
Car() : Engine(8) { } //initializes this Car with 8 cylinders
Engine::start; //start this Car by starting its engine
};
There are several similarities between these two forms of composition:
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; see below).