Aggregation & Composition

Unit 3 · Topic 3.4

Introduction

Aggregation and composition are "has-a" relationships. Aggregation: weak ownership (parts can exist independently). Composition: strong ownership (parts die with whole).

Definition

Aggregation: has-a, parts independent. Composition: has-a, parts dependent.

Code Example

// Composition
class Engine {};
class Car { Engine e; };  // Engine dies with Car
// Aggregation
class Department { vector<Employee*> staff; };  // employees independent

MCQ Practice

1. Composition is:

  • Strong ownership
  • Weak ownership
  • Inheritance
  • Polymorphism
Answer: strong.

2. Aggregation is:

  • Weak ownership
  • Strong ownership
  • Inheritance
  • None
Answer: weak.

3. Both are:

  • has-a relationships
  • is-a
  • uses-a only
  • none
Answer: has-a.

4. In composition, parts:

  • Die with whole
  • Survive
  • Are shared
  • None
Answer: die with whole.

5. Aggregation uses:

  • Pointers/references
  • Direct objects only
  • Inheritance
  • Templates
Answer: pointers/references.

Quick Revision

  • Aggregation: weak has-a.
  • Composition: strong has-a.
  • Both reuse via composition.