Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

09
Dec

How are “private inheritance” and “composition” similar?

Related Blog Items

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:
[highlight lang="CPP"]

 

 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
 };

[/highlight]

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:

  • In both cases there is exactly one Engine member object contained in every Car object
  • In neither case can users (outsiders) convert a Car* to an Engine*
  • In both cases the Car class has a start() method that calls the start() method on the contained Engine object.

There are also several distinctions:

  • The simple-composition variant is needed if you want to contain several Engines per Car
  • The private-inheritance variant can introduce unnecessary multiple inheritance
  • The private-inheritance variant allows members of Car to convert a Car* to an Engine*
  • The private-inheritance variant allows access to the protected members of the base class
  • The private-inheritance variant allows Car to override Engine's virtual functions
  • The private-inheritance variant makes it slightly simpler (20 characters compared to 28 characters) to give Car a start() method that simply calls through to the Engine's start() method

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

Popularity: 4%

You need to log on to convert this article into PDF


Related Blog Items

No Comments

No comments yet.

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image