Loading lessons...
Object Relationships
Object Relationships
Real programs join many classes. C++ describes how objects relate with a small vocabulary: composition, aggregation, association, dependency.
Composition - part of me
A composition means the whole creates and destroys its parts. An Engine inside a Car dies with the car.
struct Engine { int hp; };
struct Car {
Engine engine; // owned by value, both live and die together
Car() : engine{120} {}
};
Aggregation - I hold someone else's
Aggregation means the whole holds references to independent object. A Team points at Player instances that exist on their own.
struct Player { std::string name; };
struct Team {
std::string teamName;
std::vector<Player*> members; // borrowed, not owned
};
Association - we know each other
Association links classes without any ownership. A Doctor and a Patient know each other, but neither owns the other.
Dependency - I use it
The loosest tie: a class uses another only in a function signature.
void printTeam(const Team& team); // depends on Team
No ownership, and no member whose lifetime is stored.
Loosen the coupling
Prefer the loosest relationship that works. Favor arguments over member; favor interfaces over type names. The less a class knows, the easier it is to test.
TL;DR
- Composition: the whole owns the parts and shares their lifetime.
- Aggregation: borrowed parts that outlive the whole.
- Association: classes that relate without any ownership.
- Dependency: one class only uses the other in a parameter.
- Loose coupling and clear interfaces make classes reusable.