Loading lessons...
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.
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):
Destructors run in the reverse order: container first, then member objects.
#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:
Engine built (120 hp)
Wheel built (16 in)
Car built
Engine started
Car is moving
Car destroyed
Wheel destroyed
Engine destroyedThe 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.
| Basis | Composition (strong "has-a", "part-of") | Aggregation (weak "has-a") |
|---|---|---|
| Meaning | the part cannot exist without the whole | the part can exist independently of the whole |
| Lifetime | the part is created and destroyed with the whole | the part has its own lifetime |
| Sharing | a part belongs to one whole only | a 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 symbol | filled diamond ◆ on the whole's side | hollow diamond ◇ on the whole's side |
| Example | a house and its rooms; a car and its engine | a department and its teachers; a team and its players |
Composition (filled diamond) and aggregation (hollow diamond) in UML
#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:
CSE: Dr. Rao Dr. Iyer
Maths: Dr. Iyer
Dr. Rao still exists
House with rooms 1 and 23. Inheritance vs Containership
| Inheritance | Containership (composition / aggregation) |
|---|---|
| "is-a" relationship | "has-a" (or "part-of") relationship |
class Car : public Vehicle | class Car { Engine e; }; |
| the derived class is a kind of the base | the container uses the contained object |
derived class can access protected members | container uses only the public interface |
| base constructor is called with the class name in the initialization list | member 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 classes | looser 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.
| Basis | Classification hierarchy | Composition hierarchy |
|---|---|---|
| Relationship | is-a (kind-of) | has-a (part-of) |
| Built with | inheritance | containership (member objects) |
| Also called | generalisation/specialisation, kind-of hierarchy | aggregation, whole-part, part-of hierarchy |
| Moving down | more specialised classes (Vehicle → Car → SportsCar) | smaller parts (Car → Engine → Piston) |
| What is shared | the interface and implementation of the base | nothing; each part is a separate object |
| Question it answers | "What kind of thing is this?" | "What is this thing made of?" |
| Example | Animal → Mammal → Dog | Computer → Motherboard → CPU |
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).
#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:
Swift is a vehicle
engine: vroomKey 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.
📝 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/Wheelprogram with the order of construction and destruction. - Q2. Differentiate between aggregation and composition with examples. (5 Marks)
- Write: the comparison table and the
Department/Houseprogram. - Q3. Compare composition hierarchies with classification hierarchies. (5 Marks)
- Write: the comparison table, the diagram, and the
Carprogram that uses both. - Q4. Differentiate between inheritance and containership. When would you prefer each? (5 Marks)