Aggregation is a design principle where a class contains references to objects of other classes, representing a “has-a” relationship. Unlike composition, aggregation implies a weaker relationship between the container and its components, meaning the contained objects can exist independently of the container.
Consider a Library
class and a Book
class where the library contains books, but the books can exist independently.
#include <iostream>
#include <vector>
#include <string>
class Book {
public:
std::string title;
Book(const std::string& t) : title(t) {}
void display() const {
std::cout << "Book: " << title << std::endl;
}
};
class Library {
private:
std::vector<Book*> books; // Aggregation
public:
void addBook(Book* book) {
books.push_back(book);
}
void showBooks() const {
for (const auto& book : books) {
book->display();
}
}
};
int main() {
Book book1("1984");
Book book2("Brave New World");
Library library;
library.addBook(&book1);
library.addBook(&book2);
library.showBooks();
return 0;
}
Aspect | Aggregation | Composition |
---|---|---|
Ownership | Weak ownership | Strong ownership |
Lifecycle | Independent of the container | Dependent on the container |
Relationship | “Has-a” (weaker) | “Part-of” (stronger) |
Examples | Library and Book | Car and Engine |
#include <iostream>
#include <vector>
#include <string>
class Student {
public:
std::string name;
Student(const std::string& n) : name(n) {}
void display() const {
std::cout << "Student: " << name << std::endl;
}
};
class University {
private:
std::vector<Student*> students;
public:
void addStudent(Student* student) {
students.push_back(student);
}
void showStudents() const {
for (const auto& student : students) {
student->display();
}
}
};
int main() {
Student s1("Alice");
Student s2("Bob");
University uni;
uni.addStudent(&s1);
uni.addStudent(&s2);
uni.showStudents();
return 0;
}