🏛️Go deeper — read the bookObject-Oriented Programming in C++— runnable code & full walkthrough →

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.

🔑 Key line

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 Vehicle
struct Vehicle {
void start();
};
struct Car : public Vehicle {}; // inherits start()
// HAS-A (composition): a Car HAS-A Engine
struct Engine {
void run();
};
struct Car2 {
Engine engine; // owns an Engine
void start() {
engine.run();
} // delegates to it
}; // swap Engine freely

What this lesson walks through

  1. 01Two ways to reuse: IS-A vs HAS-A
  2. 02Inheritance couples tight; composition stays loose
  3. 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.

← Previous
C++: Name Mangling, extern C, Inheritance Access Rules, Virtual Destructor
Next →
How Virtual Dispatch Really Works (vtable indexing)