When designing Object-Oriented systems, developers constantly face a choice: Should class B inherit from class A, or should class B contain an instance of class A? This is the debate of Inheritance vs Composition.
Inheritance is used when a class is a specialized version of another class. It models an "Is-A" relationship.
Car is a Vehicle.Manager is an Employee.Dog is an Animal.If the sentence "Class B is a Class A" makes logical sense, inheritance is usually the right choice.
Composition is used when a class is composed of one or more other classes. It models a "Has-A" relationship. Instead of inheriting from a class, you instantiate it as a member variable.
Car has an Engine.University has a Library.Smartphone has a Battery.It would make no sense to say "A Car is an Engine", so a Car should not inherit from Engine.
#include <iostream>
using namespace std;
// The component class
class Engine {
public:
void start() {
cout << "Engine starting: Vroom!" << endl;
}
};
// The composite class
class Car {
private:
// Car "has an" Engine
Engine myEngine;
public:
void turnKey() {
cout << "Key turned." << endl;
// Delegating behavior to the component
myEngine.start();
}
};
int main() {
Car myCar;
myCar.turnKey();
A common design principle in modern software engineering is: "Favor object composition over class inheritance."
While inheritance is powerful, it creates tight coupling. A change in a base class can unexpectedly break all derived classes (the fragile base class problem). Deep inheritance hierarchies become difficult to understand and maintain.
Composition, on the other hand, provides loose coupling. You can easily swap out components. If a Car has an Engine, you can easily replace a gas engine with an electric engine component without rewriting the Car class, as long as they share a common interface.
Models a relationship where one object is a specialized version of another (e.g., a Dog IS an Animal).
Models a relationship where one object contains another object as part of its state (e.g., a Car HAS an Engine).
Test your understanding with 2 questions
Which relationship is best modeled by Composition?
Why might Composition be preferred over Inheritance in modern software design?
2 Modules
2 Modules