All Courses
OOP: COMPOSITION AND RELATIONSHIPS

Composition

Composition means one class owns another object as a part of itself.

Simple idea:

Whole owns part.
Part lifetime depends on whole.

Example:

Car has Engine
House has Rooms
Library has Books

Complete Example

#include <iostream>
#include <string>
#include <utility>
using namespace std;

class Engine {
private:
    string model;

public:
    explicit Engine(string engineModel) : model(move(engineModel)) {}

    void start() const {
        cout << model << " engine started" << endl;
    }
};

class Car {
private:
    Engine engine;

public:
    Car(string engineModel) : engine(move(engineModel)) {}

    void drive() const {
        engine.start();
        cout << "Car is moving" << endl;
    }
};

int main() {
    Car car("Hybrid");
    car.drive();

    return 0;
}

Output:

Hybrid engine started
Car is moving

Ownership and Lifetime

In the example:

  • Car owns Engine.
  • Engine is a data member inside Car.
  • When Car is created, its Engine is created.
  • When Car is destroyed, its Engine is destroyed automatically.

This is strong ownership.

Why Composition Is Often Preferred

Composition is often better than inheritance because:

  • It avoids deep inheritance chains.
  • It keeps classes focused.
  • It makes code easier to change.
  • It models has-a relationships clearly.
  • It supports encapsulation because the part can stay private.

Viva Answer

Composition is a strong has-a relationship where one class owns another object as a member. The contained object's lifetime is controlled by the containing object. For example, a Car has an Engine.

Quick Check

  1. In composition, who owns the part object?
  2. What happens to the part when the whole object is destroyed?
  3. Why is composition better than inheritance for Car and Engine?