Composition vs Aggregation - heshawacooray/OOP-Heshawa GitHub Wiki
Definition: Composition and Aggregation are both types of object relationships in object-oriented programming. They describe how objects can be related to other objects.
- Composition: A strong "has-a" relationship where the child object cannot exist without the parent object. When the parent object is destroyed, all its child objects are also destroyed.
- Aggregation: A weaker "has-a" relationship where the child object can exist independently of the parent object. The parent object does not own the child object, and destroying the parent does not destroy the child.
| Feature | Composition | Aggregation |
|---|---|---|
| Ownership | The parent object owns the child object | The parent object does not own the child object |
| Lifetime | Child object’s lifetime is tied to the parent | Child object’s lifetime is independent |
| Destruction | When the parent is destroyed, child objects are also destroyed | Child objects can continue to exist even after the parent is destroyed |
| Relationship Type | Strong relationship | Weak relationship |
Example code:
#include <iostream>
using namespace std;
// Composition: Car owns Engine
class Engine {
public:
Engine() {
cout << "Engine created" << endl;
}
~Engine() {
cout << "Engine destroyed" << endl;
}
};
class Car {
private:
Engine engine; // Composition: Engine is part of the Car
public:
Car() {
cout << "Car created" << endl;
}
~Car() {
cout << "Car destroyed" << endl;
}
void start() {
cout << "Car is starting..." << endl;
}
};
int main() {
Car car; // When the car is created, the engine is created
car.start();
return 0; // When car goes out of scope, both car and engine are destroyed
}