Aggregation in C++ is a relationship between two classes where one class contains or uses objects of another class without owning their lifetime. The contained objects can exist independently of the container object.
- It represents a weak has-a relationship between objects.
- The lifetime of the contained object is independent of the container object.

Consider a Company and an Employee. A company has employees, but employees can exist independently of the company.
#include
using namespace std;
class Employee {
public:
string name;
Employee(string n) {
name = n;
}
void display() {
cout << "Employee: " << name << endl;
}
};
class Company {
private:
Employee* employee;
public:
// Store the address of an existing Employee object
Company(Employee* e) {
employee = e;
}
void displayEmployee() {
employee->display();
}
};
int main() {
// Employee exists independently of Company
Employee employee("Amit");
{
Company company(&employee);
company.displayEmployee();
}
// Employee still exists after Company is destroyed
employee.display();
return 0;
}
Output
Employee: Amit Employee: Amit
For the above example:
- An Employee object is created independently.
- Its address is passed to the Company object.
- Company stores the pointer to that Employee.
- Company uses the employee object through the pointer.
- When Company is destroyed, the Employee object remains alive.
Characteristics of Aggregation
- Represents a weak has-a relationship.
- The container does not own the lifetime of the contained object.
- Both objects can exist independently.
- The contained object is created outside the container.
- Destroying the container does not destroy the contained object.
Association vs Aggregation
| Feature | Association | Aggregation |
|---|---|---|
| Relationship | General relationship between objects | Weak has-a relationship |
| Ownership | No ownership | Weak ownership |
| Object lifetime | Independent | Independent |
| Purpose | Objects interact or use each other | One object contains or refers to another |
| Example | Doctor - Patient | Company - Employee |
| Parent destruction | Does not affect the other object | Does not destroy the contained object |
| UML notation | Simple line | Hollow diamond (◇) |