Lesson 25 +30 XP

Aggregation, Composition & Containership

Aggregation, Composition & Containership

Inheritance models the "is-a" relationship: a car is a vehicle. Most objects are also built from other objects: a car has an engine and four wheels.

This "has-a" relationship is modelled by placing objects inside other objects, called containership (or nesting). This lesson covers containership, the two forms of "has-a" (aggregation and composition), and the classic comparison of composition hierarchies vs classification hierarchies.

1. Containership (Nesting of Classes)

A class can contain objects of other classes as data members. The containing class is the container; the contained objects are member objects. This is called containership, nesting or composition.

C++
class Alpha {
    ...
};
class Beta {
    ...
};
class Gamma {
    Alpha a; // a is an object of class Alpha
    Beta b;  // b is an object of class Beta
};

Constructing a container

Member objects are constructed before the container's own constructor body runs, in the order they are declared in the class. If they need arguments, the container passes them in its initialization list, using the member object names (not class names, as is done for base classes):

Gamma(arglist) : a(arglist1), b(arglist2) { dots }

Destructors run in the reverse order: container first, then member objects.

C++
#include <iostream>
using namespace std;

class Engine {
    int hp;

public:
    Engine(int h) : hp(h) {
        cout << "Engine built (" << hp << " hp)" << endl;
    }
    ~Engine() {
        cout << "Engine destroyed" << endl;
    }
    void start() {
        cout << "Engine started" << endl;
    }
};

class Wheel {
    int size;

public:
    Wheel(int s) : size(s) {
        cout << "Wheel built (" << size << " in)" << endl;
    }
    ~Wheel() {
        cout << "Wheel destroyed" << endl;
    }
};

class Car {
    Engine engine; // Car HAS-AN Engine
    Wheel wheel;   // and HAS-A Wheel (one, to keep the output short)
public:
    Car(int hp, int size) : engine(hp), wheel(size) { // member object names
        cout << "Car built" << endl;
    }
    ~Car() {
        cout << "Car destroyed" << endl;
    }
    void drive() {
        engine.start(); // the container uses its parts' public interface
        cout << "Car is moving" << endl;
    }
};

int main() {
    Car c(120, 16);
    c.drive();
    return 0;
}

Output:

OUTPUT
Engine built (120 hp)
Wheel built (16 in)
Car built
Engine started
Car is moving
Car destroyed
Wheel destroyed
Engine destroyed

The container can use only the public members of its member objects; it has no special access to their private data (unlike a derived class, which can use protected members).

2. Aggregation vs Composition

Both are "has-a" relationships. They differ in ownership and lifetime.

BasisComposition (strong "has-a", "part-of")Aggregation (weak "has-a")
Meaningthe part cannot exist without the wholethe part can exist independently of the whole
Lifetimethe part is created and destroyed with the wholethe part has its own lifetime
Sharinga part belongs to one whole onlya part may be shared by several wholes
In C++a member object (or a pointer the whole creates and deletes)a pointer or reference to an object created elsewhere
UML symbolfilled diamond ◆ on the whole's sidehollow diamond ◇ on the whole's side
Examplea house and its rooms; a car and its enginea department and its teachers; a team and its players

Composition (filled diamond) and aggregation (hollow diamond) in UMLComposition (filled diamond) and aggregation (hollow diamond) in UML

C++
#include <iostream>
using namespace std;

class Teacher {
    const char* name;

public:
    Teacher(const char* n) : name(n) {}
    const char* getName() const {
        return name;
    }
};

class Department { // AGGREGATION: holds pointers to teachers
    const char* title;
    Teacher* staff[5];
    int count;

public:
    Department(const char* t) : title(t), count(0) {}
    void add(Teacher* t) {
        if (count < 5) {
            staff[count++] = t;
        }
    }
    void show() const {
        cout << title << ":";
        for (int i = 0; i < count; i++) {
            cout << " " << staff[i]->getName();
        }
        cout << endl;
    }
    // no destructor deletes the teachers: the department does not own them
};

class Room {
    int number;

public:
    Room(int n) : number(n) {}
    int getNumber() const {
        return number;
    }
};

class House {    // COMPOSITION: owns its rooms
    Room r1, r2; // created and destroyed with the house
public:
    House() : r1(1), r2(2) {}
    void show() const {
        cout << "House with rooms " << r1.getNumber() << " and " << r2.getNumber() << endl;
    }
};

int main() {
    Teacher a("Dr. Rao"), b("Dr. Iyer"); // teachers exist on their own
    {
        Department cse("CSE"), maths("Maths");
        cse.add(&a);
        cse.add(&b);
        maths.add(&b); // Dr. Iyer is shared
        cse.show();
        maths.show();
    } // departments gone...
    cout << a.getName() << " still exists" << endl; // ...teachers remain

    House h; // rooms are created with the house
    h.show();
    return 0;
}

Output:

OUTPUT
CSE: Dr. Rao Dr. Iyer
Maths: Dr. Iyer
Dr. Rao still exists
House with rooms 1 and 2

3. Inheritance vs Containership

InheritanceContainership (composition / aggregation)
"is-a" relationship"has-a" (or "part-of") relationship
class Car : public Vehicleclass Car { Engine e; };
the derived class is a kind of the basethe container uses the contained object
derived class can access protected memberscontainer uses only the public interface
base constructor is called with the class name in the initialization listmember constructor is called with the object name
supports run-time polymorphism (virtual functions)no polymorphism through the container itself
tighter coupling: changes in the base affect all derived classeslooser coupling: the part can be replaced

Rule of thumb: use inheritance only when the "is-a" test passes; otherwise prefer composition ("favour composition over inheritance"). A Stack has an array, it is not an array.

4. Composition Hierarchies vs Classification Hierarchies

Object oriented systems organise classes in two kinds of hierarchy.

BasisClassification hierarchyComposition hierarchy
Relationshipis-a (kind-of)has-a (part-of)
Built withinheritancecontainership (member objects)
Also calledgeneralisation/specialisation, kind-of hierarchyaggregation, whole-part, part-of hierarchy
Moving downmore specialised classes (Vehicle → Car → SportsCar)smaller parts (Car → Engine → Piston)
What is sharedthe interface and implementation of the basenothing; each part is a separate object
Question it answers"What kind of thing is this?""What is this thing made of?"
ExampleAnimal → Mammal → DogComputer → Motherboard → CPU

A classification hierarchy (is-a) beside a composition hierarchy (has-a)A classification hierarchy (is-a) beside a composition hierarchy (has-a)

Real designs use both: a SportsCar is a Car (classification) and has an Engine (composition).

C++
#include <iostream>
using namespace std;

class Engine { // part
public:
    void start() {
        cout << "  engine: vroom" << endl;
    }
};

class Vehicle { // classification: general
protected:
    const char* name;

public:
    Vehicle(const char* n) : name(n) {}
    void describe() {
        cout << name << " is a vehicle" << endl;
    }
};

class Car : public Vehicle { // Car IS-A Vehicle
    Engine engine;           // Car HAS-AN Engine
public:
    Car(const char* n) : Vehicle(n) {}
    void go() {
        describe();
        engine.start();
    }
};

int main() {
    Car c("Swift");
    c.go();
    return 0;
}

Output:

OUTPUT
Swift is a vehicle
  engine: vroom
💡 Tip

Key points to remember

  • Containership = objects of other classes as data members ("has-a"); member objects are built before the container and destroyed after it.
  • Pass arguments to member objects in the initialization list using the object names.
  • Composition: the part dies with the whole (filled diamond). Aggregation: the part lives independently and may be shared (hollow diamond).
  • Classification hierarchy = is-a = inheritance; composition hierarchy = has-a = containership.
  • Prefer composition unless the "is-a" test clearly passes.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What is containership? How are constructors of member objects invoked? Write a program. (5 Marks)
  • Write: the definition, the initialization list with object names, and the Car/Engine/Wheel program with the order of construction and destruction.
  • Q2. Differentiate between aggregation and composition with examples. (5 Marks)
  • Write: the comparison table and the Department/House program.
  • Q3. Compare composition hierarchies with classification hierarchies. (5 Marks)
  • Write: the comparison table, the diagram, and the Car program that uses both.
  • Q4. Differentiate between inheritance and containership. When would you prefer each? (5 Marks)