All Courses
OOP: COMPOSITION AND RELATIONSHIPS

Aggregation

Aggregation is a weak has-a relationship.

Simple idea:

One object refers to another object,
but it does not fully own its lifetime.

Example:

Course has a Teacher
Team has Players
Department has Professors

The teacher, players, or professors can exist independently.

Complete Example

#include <iostream>
#include <string>
#include <utility>
using namespace std;

class Teacher {
private:
    string name;

public:
    explicit Teacher(string teacherName) : name(move(teacherName)) {}

    const string& getName() const {
        return name;
    }
};

class Course {
private:
    const Teacher& teacher;
    string title;

public:
    Course(string courseTitle, const Teacher& assignedTeacher)
        : teacher(assignedTeacher), title(move(courseTitle)) {}

    void display() const {
        cout << title << " is taught by " << teacher.getName() << endl;
    }
};

int main() {
    Teacher teacher("Dr. Ahmed");

    Course oop("OOP in C++", teacher);
    oop.display();

    return 0;
}

Output:

OOP in C++ is taught by Dr. Ahmed

Aggregation vs Composition

Topic Composition Aggregation
Ownership strong weak
Lifetime part depends on whole part can exist independently
Example Car owns Engine Course refers to Teacher
C++ form direct member object reference, pointer, or external object

Important Lifetime Warning

If a class stores a reference or pointer to another object, that other object must remain alive while it is being used.

This is safe:

Teacher teacher("Dr. Ahmed");
Course course("OOP", teacher);

The teacher object exists while course uses it.

Viva Answer

Aggregation is a weak has-a relationship where one object uses or refers to another object, but does not own its lifetime. The related object can exist independently before and after the aggregating object.

Quick Check

  1. Does aggregation imply strong ownership?
  2. Can a Teacher exist without a Course?
  3. What is the biggest lifetime danger in aggregation?