Example
Example
#include <string>
using namespace std;
class Employee {
private:
int id;
string name;
public:
Employee(int id, string name) {
this->id = id;
this->name = name;
}
void displayInfo() {
cout << "Employee ID: " << id << ", Name: " << name << endl;
}
};
class University {
private:
int id;
string name;
Employee* employee; // Aggregation
public:
University(int id, string name, Employee* emp) {
this->id = id;
this->name = name;
this->employee = emp;
}
void displayInfo() {
cout << "University ID: " << id << ", Name: " << name << endl;
cout << "Associated Employee: ";
employee->displayInfo();
}
};
int main() {
Employee emp(1, "Alice");
University uni(101, "OpenAI University", &emp);
uni.displayInfo();
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Employee {
private:
int id;
string name;
public:
Employee(int id, string name) {
this->id = id;
this->name = name;
}
void displayInfo() {
cout << "Employee ID: " << id << ", Name: " << name << endl;
}
};
class University {
private:
int id;
string name;
Employee* employee; // Aggregation
public:
University(int id, string name, Employee* emp) {
this->id = id;
this->name = name;
this->employee = emp;
}
void displayInfo() {
cout << "University ID: " << id << ", Name: " << name << endl;
cout << "Associated Employee: ";
employee->displayInfo();
}
~University() {
cout << "University object '" << name << "' is destroyed." << endl;
}
};
int main() {
Employee emp(1, "Alice");
{
// Begin scoped block
University uni(101, "OpenAI University", &emp);
uni.displayInfo();
return 0;
}
Imagine you hire a teacher (the Employee) and temporarily assign them to a
university (University) for a project.
The teacher (employee) exists on their own — they don’t depend on any one
university to exist.
Once the project ends, the university closes down — it goes out of scope and is
destroyed.
But the teacher is still there! They weren’t destroyed because they weren't owned
by the university — they just worked there temporarily.
That’s aggregation: the university knows about the employee and uses them, but it
doesn’t own or manage their life. So when the university is destroyed, the employee
stays alive.