Search code examples
c++private-inheritance

Why does private inheritance increase the probability, as compared to composition, that someone will break my code?


The author of this article states that

"Normally you don't want to have access to the internals of too many other classes, and private inheritance gives you some of this extra power (and responsibility). But private inheritance isn't evil; it's just more expensive to maintain, since it increases the probability that someone will change something that will break your code."

Assume the following code where Car inherits from Engine privately :

#include <iostream>
using namespace std;

class Engine
{
    int numCylinders;
    public:
    class exception{};
    Engine(int i) { if( i < 4 ) throw exception(); numCylinders = i; }
    void start() { cout << "Engine started " << numCylinders << " cylinders" << endl; }
};

class Car : private Engine          
{    
    public:
    Car(int i) : Engine(i) {}
    using Engine::start;
};

int main()
{
    try
    {
        Car c(4);
        c.start();
    }
    catch( Engine::exception& )
    {
        cout << "A Car cannot have less than 4 cylinders" << endl;
    }
}

My question is : how a Car can break this code, by setting up, for example, its Engine with less than 4 cylinders, using private inheritance and without protected members in the base class ?


Solution

  • I think the issue isn't that Car can break your Engine code, but rather that by changing Engine, someone can break your Car code. Inheritance represents a much tighter coupling than composition, so that changes in Engine are more likely to break a class that inherits from it rather than contains it. In the case of C++, an even looser coupling is achieved by having Car contain an Engine pointer or smart pointer.