CLOSE
Updated on 25 Jun, 20266 mins read 11 views

Historical Motivation

Early OOP heavily emphasized:

Inheritance

The belief was:

Inheritance = Reuse

Example:

class Animal
{
};

class Dog : public Animal
{
};

This looked elegant.

But large systems revealed problems:

Deep inheritance trees

Fragile base classes

Unexpected side effects

Complex dependencies

Engineers began searching for alternatives.

They discovered:

Composition

which 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 Independently

This is defining characteristic.

Real-World Analogy

Consider:

House

and

Room

A house contains rooms.

Question:

Can a room exist independently?

Usually:

No

Destroy the house:

House demolished

Rooms disapper.

The room's lifecycle depends on the house.

This is Composition.

UML Notation

Composition uses:

Filled Diamond

Diagram:

House тЧЖ-------- Room

The 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 Ownership

The 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:

Room

is 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: No

Composition confirmed.

 

Buy Me A Coffee

Leave a comment

Your email address will not be published. Required fields are marked *

Your experience on this site will be improved by allowing cookies Cookie Policy