Composition vs Inheritance
Two ways to reuse code
| Inheritance | Composition | |
|---|---|---|
| Relationship | is-a | has-a |
| Example | Circle is a Shape | Car has an Engine |
| Coupling | tight: derived depends on base internals | loose: uses the part's public interface |
| Change at runtime | no | yes (swap the part) |
| Exposes | all public base functions | only what you choose |
Composition example
class Car {
Engine engine_; // a member object
std::vector<Wheel> wheels_;
public:
void start() { engine_.start(); } // delegate
};
Classic inheritance mistake
class Stack : public std::vector<int> { ... }; // ❌
Now users can call insert or erase in the middle — breaking the stack rules. Composition fixes it:
class Stack { std::vector<int> data_; public: void push(int); int pop(); }; // ✅
The Liskov Substitution Principle (LSP)
A derived class must be usable anywhere its base is, without surprises.
Famous counterexample: Square inherits Rectangle. set_width(5) on a Square must also change its height — code that expects rectangles to change width independently breaks.
Strategy via composition
Instead of class DiscountedOrder : Order, class FestivalOrder : Order… give Order a pluggable discount strategy object (or a std::function). New behaviours without new subclasses.
Rules of thumb ✅
- Use inheritance for genuine is-a with polymorphism (interfaces, shape hierarchies)
- Use composition for has-a and for reusing implementation
- Keep inheritance hierarchies shallow (1–2 levels)
- If you find yourself overriding functions to "disable" them, inheritance is wrong
Example
#include <functional>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
// Composition: a Stack HAS a vector and exposes only stack operations
class Stack {
public:
void push(int x) { data_.push_back(x); }
int pop() {
if (data_.empty()) throw std::out_of_range("pop from empty stack");
int top = data_.back();
data_.pop_back();
return top;
}
bool empty() const { return data_.empty(); }
private:
std::vector<int> data_; // insert/erase in the middle are NOT exposed
};
class Engine {
public:
void start() { running_ = true; std::cout << " engine started\n"; }
bool running() const { return running_; }
private:
bool running_ = false;
};
class Car { // a Car HAS an Engine
public:
explicit Car(std::string model) : model_(std::move(model)) {}
void drive() {
if (!engine_.running()) engine_.start(); // delegation
std::cout << " " << model_ << " is driving\n";
}
private:
std::string model_;
Engine engine_;
};
// Strategy by composition: swap the discount rule without subclasses
class Order {
public:
using Discount = std::function<double(double)>;
Order(double amount, Discount d) : amount_(amount), discount_(std::move(d)) {}
void set_discount(Discount d) { discount_ = std::move(d); }
double total() const { return amount_ - discount_(amount_); }
private:
double amount_;
Discount discount_;
};
int main() {
Stack s;
for (int x : { 1, 2, 3 }) s.push(x);
std::cout << "popped:";
while (!s.empty()) std::cout << ' ' << s.pop();
std::cout << '\n';
Car c("Hyundai i20");
c.drive();
c.drive();
Order o(5000, [](double) { return 0.0; });
std::cout << "normal price: " << o.total() << '\n';
o.set_discount([](double a) { return a * 0.10; }); // Dashain sale
std::cout << "festival price: " << o.total() << '\n';
o.set_discount([](double a) { return a > 3000 ? 500.0 : 0.0; }); // flat coupon
std::cout << "coupon price: " << o.total() << '\n';
return 0;
}
/* Output:
popped: 3 2 1
engine started
Hyundai i20 is driving
Hyundai i20 is driving
normal price: 5000
festival price: 4500
coupon price: 4500
*/