What is the difference between inheritance and composition?
Inheritance models an is a relationship, where a child class is a kind of the parent, and it reuses the parent by extending it. Composition models a has a relationship, where one class holds another class as a field and uses its behaviour. Modern advice is to favour composition because it is more flexible and creates looser coupling than deep inheritance.
- Inheritance models an is a relationship, while composition models a has a relationship.
- Composition holds another class as a field, which keeps designs flexible and loosely coupled.
- Modern advice is to favour composition over inheritance for most designs.
The simple test: is a versus has a
Ask yourself whether the relationship is an is a or a has a. A Dog is an Animal, so inheritance fits. A Car has an Engine, so composition fits. Getting this test right is most of the answer.
Inheritance example
class Animal { public: void eat() {} };
class Dog : public Animal { }; // Dog is an Animalclass Animal { void eat() {} }
class Dog extends Animal { } // Dog is an Animalclass Animal:
def eat(self): ...
class Dog(Animal): # Dog is an Animal
passComposition example
class Engine { public: void start() {} };
class Car {
Engine engine; // Car has an Engine
public:
void start() { engine.start(); }
};class Engine { void start() {} }
class Car {
private Engine engine = new Engine(); // Car has an Engine
void start() { engine.start(); }
}class Engine:
def start(self): ...
class Car:
def __init__(self):
self.engine = Engine() # Car has an Engine
def start(self):
self.engine.start()Why teams often prefer composition
- Flexibility: you can swap the inner object for another type at run time.
- Loose coupling: the outer class depends on behaviour, not on a rigid parent hierarchy.
- Avoids fragile base class problems where a parent change breaks many children.
The phrase interviewers love is favour composition over inheritance. Say inheritance for a clear is a relationship and composition for a has a relationship, then explain that composition keeps designs flexible. That single sentence signals real experience.
Frequently asked questions
Why is composition often preferred over inheritance?
Composition lets you swap the inner object at run time and avoids fragile deep hierarchies, so a change in a base class is less likely to break many children.
What is the fragile base class problem?
It is when a change to a parent class unexpectedly breaks child classes that depended on its behaviour, a common risk with deep inheritance.
Common follow up questions
Related interview questions
Want the full OOP guide?
Read every OOP concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the OOP guide All OOP questions