oops · high
Composition vs Inheritance (IS-A vs HAS-A)
The most common OOP design question: when to inherit and when to compose. IS-A vs HAS-A, the fragile-base-class coupling of inheritance, why 'prefer composition over inheritance' is the default advice, and the Liskov rule for when inheritance is actually correct.
Inheritance models IS-A and couples the derived type to the base's implementation (fragile base class). Composition models HAS-A: the class owns a member and delegates to it, staying loosely coupled and swappable. Prefer composition; use inheritance only for a true, substitutable IS-A.
The code
// IS-A (inheritance): a Car IS-A Vehiclestruct Vehicle { void start();};struct Car : public Vehicle {}; // inherits start()
// HAS-A (composition): a Car HAS-A Enginestruct Engine { void run();};struct Car2 { Engine engine; // owns an Engine void start() { engine.run(); } // delegates to it}; // swap Engine freelyWhat this lesson walks through
- 01Two ways to reuse: IS-A vs HAS-A
- 02Inheritance couples tight; composition stays loose
- 03Prefer composition — inherit only for a true IS-A
Inheritance says IS-A: a Car IS-A Vehicle, inheriting its interface. Composition says HAS-A: a Car HAS-A Engine and delegates to it. Both reuse code — but they couple very differently.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Composition vs Inheritance (IS-A vs HAS-A) and 100+ animated C++ interview lessons.