All Courses
OOP: COMPOSITION AND RELATIONSHIPS

Association

Association means two classes are connected in some meaningful way.

It is a general relationship. It does not necessarily mean ownership.

Example:

Doctor treats Patient
Student enrolls in Course
Customer places Order

Complete Example

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

class Patient {
private:
    string name;

public:
    explicit Patient(string patientName) : name(move(patientName)) {}

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

class Doctor {
private:
    string name;
    vector<const Patient*> patients;

public:
    explicit Doctor(string doctorName) : name(move(doctorName)) {}

    void addPatient(const Patient& patient) {
        patients.push_back(&patient);
    }

    void displayPatients() const {
        cout << "Doctor: " << name << endl;

        for (const Patient* patient : patients) {
            cout << "Patient: " << patient->getName() << endl;
        }
    }
};

int main() {
    Patient patient1("Mina");
    Patient patient2("Rafiq");

    Doctor doctor("Dr. Karim");
    doctor.addPatient(patient1);
    doctor.addPatient(patient2);

    doctor.displayPatients();

    return 0;
}

Output:

Doctor: Dr. Karim
Patient: Mina
Patient: Rafiq

Association Can Be One-Way or Two-Way

One-way association:

Doctor knows Patient
Patient does not store Doctor

Two-way association:

Doctor knows Patient
Patient also knows Doctor

Two-way association is more complex because both objects must keep their relationship consistent.

Association vs Aggregation

Aggregation is usually a special kind of association where one object represents a whole and the other represents a part.

Association is more general:

Object A is connected to Object B.

Viva Answer

Association is a general relationship where two objects are connected or communicate with each other. It does not necessarily imply ownership. It can be one-way or two-way.

Quick Check

  1. Does association always mean ownership?
  2. What is one-way association?
  3. Why is two-way association harder to maintain?