0% found this document useful (0 votes)
14 views13 pages

OOP Aggregation Exercises in C++

The document presents a series of programming exercises focused on aggregation in Object-Oriented Programming (OOP). Each exercise involves creating classes that demonstrate a 'has-a' relationship, allowing objects to exist independently while being associated with other objects, such as schools with students, libraries with books, and departments with employees. Key concepts covered include aggregation, encapsulation, and object management.

Uploaded by

af904250
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views13 pages

OOP Aggregation Exercises in C++

The document presents a series of programming exercises focused on aggregation in Object-Oriented Programming (OOP). Each exercise involves creating classes that demonstrate a 'has-a' relationship, allowing objects to exist independently while being associated with other objects, such as schools with students, libraries with books, and departments with employees. Key concepts covered include aggregation, encapsulation, and object management.

Uploaded by

af904250
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Here are some programming exercises based on Aggregation in Object-Oriented Programming (OOP).

Aggregation represents a "has-a" relationship, where one object can contain or reference other objects,
but the contained objects can exist independently of the containing object.

Exercise 1: School and Student (Aggregation)

Objective:
Create a School class that aggregates Student objects. Each student is associated with a school, but can
exist independently from the school (i.e., a student can belong to multiple schools or exist without a
school).

Solution:

#include <iostream>

#include <vector>

using namespace std;

// Student class

class Student {

private:

string name;

public:

// Constructor to initialize student's name

Student(string n) : name(n) {}

// Method to get the student's name

string getName() const {

return name;

};

// School class (aggregates multiple Students)


class School {

private:

vector<Student*> students; // School "has many" Students (Aggregation)

public:

// Method to add a student to the school

void addStudent(Student* student) {

students.push_back(student);

// Method to display all students in the school

void displayStudents() const {

if ([Link]()) {

cout << "No students in the school." << endl;

return;

cout << "Students in the school:" << endl;

for (const auto& student : students) {

cout << student->getName() << endl;

};

int main() {

// Create some Student objects

Student student1("John Doe");

Student student2("Jane Smith");

Student student3("Sam Brown");


// Create a School object

School school;

// Add students to the school

[Link](&student1);

[Link](&student2);

[Link](&student3);

// Display all students in the school

[Link]();

return 0;

Exercise 2: Library and Books (Aggregation)

Objective:
Create a Library class that aggregates Book objects. A library "has many" books, but books can exist
independently of the library.

Solution:

#include <iostream>

#include <vector>

using namespace std;

// Book class

class Book {

private:

string title;

public:
// Constructor to initialize book title

Book(string t) : title(t) {}

// Method to get the book's title

string getTitle() const {

return title;

};

// Library class (aggregates multiple Books)

class Library {

private:

vector<Book*> books; // Library "has many" Books (Aggregation)

public:

// Method to add a book to the library

void addBook(Book* book) {

books.push_back(book);

// Method to display all books in the library

void displayBooks() const {

if ([Link]()) {

cout << "No books in the library." << endl;

return;

cout << "Books in the library:" << endl;

for (const auto& book : books) {

cout << book->getTitle() << endl;


}

};

int main() {

// Create some Book objects

Book book1("The Catcher in the Rye");

Book book2("To Kill a Mockingbird");

Book book3("1984");

// Create a Library object

Library library;

// Add books to the library

[Link](&book1);

[Link](&book2);

[Link](&book3);

// Display all books in the library

[Link]();

return 0;

Exercise 3: Department and Employee (Aggregation)

Objective:
Create a Department class that aggregates Employee objects. Each department has many employees,
but employees can exist without being part of a department.

Solution:
#include <iostream>

#include <vector>

using namespace std;

// Employee class

class Employee {

private:

string name;

string position;

public:

// Constructor to initialize employee's name and position

Employee(string n, string p) : name(n), position(p) {}

// Method to display employee's details

void display() const {

cout << "Employee: " << name << ", Position: " << position << endl;

};

// Department class (aggregates multiple Employees)

class Department {

private:

vector<Employee*> employees; // Department "has many" Employees (Aggregation)

public:

// Method to add an employee to the department

void addEmployee(Employee* employee) {

employees.push_back(employee);
}

// Method to display all employees in the department

void displayEmployees() const {

if ([Link]()) {

cout << "No employees in the department." << endl;

return;

cout << "Employees in the department:" << endl;

for (const auto& employee : employees) {

employee->display();

};

int main() {

// Create some Employee objects

Employee emp1("John", "Manager");

Employee emp2("Sarah", "Developer");

Employee emp3("Mike", "Designer");

// Create a Department object

Department dept;

// Add employees to the department

[Link](&emp1);

[Link](&emp2);

[Link](&emp3);
// Display all employees in the department

[Link]();

return 0;

Exercise 4: University and Courses (Aggregation)

Objective:
Create a University class that aggregates Course objects. Each university offers many courses, and
courses can exist independently of a specific university.

Solution:

#include <iostream>

#include <vector>

using namespace std;

// Course class

class Course {

private:

string courseName;

public:

// Constructor to initialize course name

Course(string name) : courseName(name) {}

// Method to get the course name

string getCourseName() const {

return courseName;

};
// University class (aggregates multiple Courses)

class University {

private:

vector<Course*> courses; // University "offers many" Courses (Aggregation)

public:

// Method to add a course to the university

void addCourse(Course* course) {

courses.push_back(course);

// Method to display all courses offered by the university

void displayCourses() const {

if ([Link]()) {

cout << "No courses offered." << endl;

return;

cout << "Courses offered by the university:" << endl;

for (const auto& course : courses) {

cout << course->getCourseName() << endl;

};

int main() {

// Create some Course objects

Course course1("Computer Science");

Course course2("Physics");
Course course3("Mathematics");

// Create a University object

University uni;

// Add courses to the university

[Link](&course1);

[Link](&course2);

[Link](&course3);

// Display all courses offered by the university

[Link]();

return 0;

Exercise 5: Team and Player (Aggregation)

Objective:
Create a Team class that aggregates Player objects. The team "has many" players, but players can exist
independently and can belong to multiple teams.

Solution:

#include <iostream>

#include <vector>

using namespace std;

// Player class

class Player {

private:

string name;
string position;

public:

// Constructor to initialize player's name and position

Player(string n, string p) : name(n), position(p) {}

// Method to display player's details

void display() const {

cout << "Player: " << name << ", Position: " << position << endl;

};

// Team class (aggregates multiple Players)

class Team {

private:

vector<Player*> players; // Team "has many" Players (Aggregation)

public:

// Method to add a player to the team

void addPlayer(Player* player) {

players.push_back(player);

// Method to display all players in the team

void displayPlayers() const {

if ([Link]()) {

cout << "No players in the team." << endl;

return;

}
cout << "Players in the team:" << endl;

for (const auto& player : players) {

player->display();

};

int main() {

// Create some Player objects

Player player1("Alice", "Forward");

Player player2("Bob", "Midfielder");

Player player3("Charlie", "Defender");

// Create a Team object

Team team;

// Add players to the team

[Link](&player1);

[Link](&player2);

[Link](&player3);

// Display all players in the team

[Link]();

return 0;

Key Concepts Covered:


 Aggregation: Represents a "has-a" relationship where one object can contain or reference other
objects, but those contained objects can exist independently.

 Encapsulation: Classes keep their attributes and behaviors within themselves, and provide public
interfaces to interact with their data.

 Object Construction and Management: Managing relationships between objects, including


adding and displaying the associated objects.

These exercises should help you understand **aggregation

**, how objects can reference other objects without owning them, and how to create meaningful
relationships between classes.

Common questions

Powered by AI

The provided coding exercises illustrate the management of object relationships through aggregation, where container classes like School, Library, and Team manage relationships with component classes such as Student, Book, and Player by storing pointers in vectors. This setup allows for dynamic addition and removal of components, encapsulating how relationships are maintained without owning the lifecycle of the components. Methods like addStudent and displayStudents in the School class exemplify how objects are managed collectively, yet can exist independently, facilitating flexible object association and interaction .

The object-oriented design principles in the coding exercises include encapsulation, aggregation, and modularity. Each class in the exercises encapsulates its data and behavior, exposing them through public methods. Aggregation is evident where classes such as School and Library manage collections of Student or Book objects using vectors of pointers, allowing contained objects to exist independently. Modularity is demonstrated by decomposing functionalities into self-contained classes and methods, making them reusable, maintainable, and easier to test. These principles collectively lead to designs that are extensible and adaptable to changes in requirements, showcasing a robust application of OOP .

The advantages of implementing aggregation include enhanced flexibility and reusability of objects, as classes like Course or Player can exist independently and be associated with different containers, promoting modularity and reducing code duplication. Aggregation also simplifies object management by allowing dynamic associations, such as adding or removing students to a school. Potential drawbacks include increased complexity in managing object lifecycles and relationships, as there must be careful handling of object references to prevent memory leaks or dangling pointers, particularly when objects are not owned by any specific container .

Flexibility in class relationships is achieved using aggregation by decoupling the existence of objects from the containers that reference them. For example, in the University and Courses relationship, courses are aggregated via a vector in the University class but can exist without the university, allowing courses to be reassigned to different universities or dynamically added and removed. Similarly, in the Team and Player exercise, players can belong to multiple teams or none, reflecting real-world flexibility in team management. This design principle allows objects to maintain associations with multiple containers, enhancing reusability and adaptability across diverse contexts .

Aggregation supports the reuse of objects across different contexts by allowing objects to exist independently and be shared among multiple containers. For instance, Courses can be offered by various Universities, and Players can participate in multiple Teams. This design allows objects to be reallocated or reassigned without needing to recreate them, thus facilitating reuse and saving resources. Aggregation leverages pointers or references to manage object associations, enabling objects like Books or Students to be dynamically added to Libraries or Schools, thus appearing in different contexts without sacrificing independence .

Aggregation in Object-Oriented Programming is used to represent a 'has-a' relationship between objects, where the lifetime of the component objects can be independent of the parent object. In the context of a School and Student relationship, aggregation is implemented by creating a School class that contains references to multiple Student objects. Each student can exist independently of the school, meaning a student can belong to multiple schools or exist without a school. This structure allows flexible association and management of Student objects within the School class using a vector to store pointers to Student instances .

In a Library and Books aggregation, the Library class holds references to Book objects without owning their lifecycle, meaning Books can exist independently of a Library and can be shared with or belong to multiple Libraries. This contrasts with a simple containment relationship where the contained objects' lifecycle is managed by the containing object, leading to strong dependency. The aggregation is implemented in the Library class, which contains a vector of pointers to Book objects, allowing books to be added and displayed independently .

The significance of having objects that can exist independently in an aggregation relationship is that it allows greater flexibility and reusability of the objects. For instance, in the University and Courses aggregation example, courses are designed to exist independently of any specific university, meaning a course can be offered by multiple universities or none at all. This independence facilitates the reutilization of Course objects across different University instances without restricting their use or lifecycle, enabling dynamic and scalable design patterns in object-oriented systems .

The Player and Team aggregation model reflects real-world sports team dynamics by allowing players to belong to multiple teams or exist independently, similar to how athletes may play for different teams, such as national and club teams, or switch teams throughout their careers. In this model, the Team class aggregates Player objects via a vector, maintaining a roster of players without taking ownership of the players' lifecycle, enabling teams to manage their rosters flexibly and players to exist outside team structures, facilitating trades, transfers, or individual growth .

Encapsulation in the context of Department and Employee classes is achieved by hiding the internal details of these classes—such as attributes and methods—behind public interfaces, which ensures that the only way to interact with the objects is through these interfaces. The Department class aggregates Employee objects via a private vector storing pointers to Employee instances, offering methods like addEmployee and displayEmployees to manage these objects. Employee details like name and position are encapsulated within the Employee class and exposed through public methods such as display, ensuring data integrity and controlled access .

You might also like