Historical Motivation
Early OOP heavily emphasized:
InheritanceThe belief was:
Inheritance = ReuseExample:
class Animal
{
};
class Dog : public Animal
{
};This looked elegant.
But large systems revealed problems:
Deep inheritance trees
Fragile base classes
Unexpected side effects
Complex dependenciesEngineers began searching for alternatives.
They discovered:
Compositionwhich often produced simpler, more maintainable systems.
What Is Composition?
Definition:
Composition is a whole-part relationship where the whole exclusively owns the parts, and the parts cannot exist independently.
Key phrase:
Cannot Exist IndependentlyThis is defining characteristic.
Real-World Analogy
Consider:
Houseand
RoomA house contains rooms.
Question:
Can a room exist independently?Usually:
NoDestroy the house:
House demolishedRooms disapper.
The room's lifecycle depends on the house.
This is Composition.
UML Notation
Composition uses:
Filled DiamondDiagram:
House тЧЖ-------- RoomThe diamond is placed on:
The Owner side.
Meaning:
House owns Rooms.Ownership Mental Model
Think of ownership levels:
Association = Relationship
|
|
Aggregation = Weak Ownership
|
|
Composition = Strong OwnershipThe Lifecycle Rule
The most important Composition rule:
If the whole dies, the parts die.
Remember this forever.
C++ Example
Room:
class Room
{
};House:
class House
{
private:
vector<Room> rooms;
};Notice:
Roomis stored directly.
Not:
Room*This implies ownership.
Why This Is Composition
Question: Who creates Rooms?
Answer: House
Question: Who destroys Rooms?
Answer: House
Question: Can Rooms survive independently?
Answer: NoComposition confirmed.
Leave a comment
Your email address will not be published. Required fields are marked *


