ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Aggregation
    Object Oriented ProgrammingTopic 13 of 24

    Aggregation

    6 minread
    1,039words
    Intermediatelevel

    Aggregation in Object-Oriented Programming (OOP)

    Aggregation is a design principle in object-oriented programming (OOP) that represents a "has-a" relationship between two classes, similar to composition. However, in aggregation, the relationship between the objects is looser, and the contained object can exist independently of the container object.

    In simpler terms, aggregation models a relationship where one object (the "whole") contains or is associated with other objects (the "parts"), but the parts can outlive the whole. If the container object is destroyed, the contained objects (parts) continue to exist.

    Key Characteristics of Aggregation

    • "Has-a" relationship: One object is composed of or associated with another object.
    • Independence: The lifetime of the contained object is not dependent on the lifetime of the container object.
    • Looser coupling: The contained object can exist without the container object, allowing for more flexibility and reusability.
    • Shared ownership: Aggregation typically means that the contained objects can be shared between multiple container objects, which makes it different from composition where the contained object is tightly bound to the container.

    Composition vs Aggregation

    • Composition is a stronger form of aggregation. In composition, the part cannot exist without the whole, whereas in aggregation, the part can exist independently.
    • In aggregation, objects are typically not destroyed when the container object is destroyed. The contained objects can continue to exist elsewhere.

    When to Use Aggregation

    • When one object has another, but the contained object can exist independently of the container.
    • When you want to represent a relationship where the contained objects can belong to multiple container objects or can outlive the container.
    • When the lifetime of the contained objects is not bound to the lifetime of the container.

    Example of Aggregation in C++

    Consider a scenario where a Department has Employees. The Department does not create the Employees, and Employees can exist independently of the Department (i.e., an employee can be transferred to another department).

    Example Code:

    #include <iostream>
    #include <vector>
    #include <string>
    using namespace std;
    
    class Employee {
    public:
        string name;
        int id;
    
        // Constructor
        Employee(const string& name, int id) : name(name), id(id) {}
    
        // Display Employee info
        void display() {
            cout << "Employee: " << name << ", ID: " << id << endl;
        }
    };
    
    class Department {
    private:
        string departmentName;
        vector<Employee*> employees;  // Aggregation: Department has Employees (but employees exist independently)
    
    public:
        // Constructor
        Department(const string& name) : departmentName(name) {}
    
        // Add Employee to the department
        void addEmployee(Employee* emp) {
            employees.push_back(emp);
        }
    
        // Display department and employees info
        void display() {
            cout << "Department: " << departmentName << endl;
            for (auto emp : employees) {
                emp->display();
            }
        }
    };
    
    int main() {
        // Creating Employees (independent objects)
        Employee emp1("John Doe", 1);
        Employee emp2("Jane Smith", 2);
        
        // Creating Department and associating it with Employees
        Department dept("IT Department");
        dept.addEmployee(&emp1);
        dept.addEmployee(&emp2);
    
        // Display the department and its employees
        dept.display();
        
        return 0;
    }
    

    Explanation:

    1. Aggregation Relationship: In this example, the Department has Employees, but the Employees exist independently of the Department. An Employee can exist without being part of a Department, and it can be transferred from one department to another. The Department is not responsible for the lifecycle of the Employee objects, meaning if the Department is destroyed, the Employee objects will still exist.

    2. Employee Objects: The Employee objects are created independently. The Department class simply holds pointers to these Employee objects.

    3. Shared Ownership: Multiple Department objects could have references to the same Employee object, which is an important characteristic of aggregation. For example, the same Employee could be associated with different departments at different times (or at once).

    4. No Dependency on Lifetime: If the Department object is destroyed, the Employee objects still remain in existence (they are not destroyed with the Department object).

    Output:

    Department: IT Department
    Employee: John Doe, ID: 1
    Employee: Jane Smith, ID: 2
    

    Advantages of Aggregation

    1. Looser Coupling: The contained objects (parts) are not dependent on the container object for their lifecycle. This makes it easier to reuse and maintain the parts, as they can be shared by multiple containers.

    2. Flexibility: Aggregation allows greater flexibility in modeling relationships where the contained objects can exist independently of the container. This is particularly useful in scenarios where objects may need to be shared or reused across multiple parts of a system.

    3. Modularity: Since the contained objects are not tightly bound to the container, it becomes easier to change or extend the system without affecting other parts of the system.

    Disadvantages of Aggregation

    1. Complexity in Lifecycle Management: Since the contained objects do not automatically get destroyed when the container is destroyed, it becomes important to ensure proper management of object lifetimes to avoid memory leaks or dangling pointers.

    2. Less Strong Ownership: Since the container class does not own the contained objects, it is up to the developer to ensure that the objects are managed correctly and that there are no issues when the objects are shared between different parts of the system.

    Comparison: Aggregation vs Inheritance

    • Aggregation represents a has-a relationship, which is more flexible than inheritance. Aggregation is used when an object contains another, but the contained object can exist independently of the container.
    • Inheritance, on the other hand, represents an is-a relationship where a subclass inherits properties and behavior from a superclass.

    For example, a Car might have a Wheel (aggregation), but a Car is a Vehicle (inheritance).

    Summary

    • Aggregation is a relationship where one class "has" or "contains" another, but the contained object can exist independently of the containing object.
    • The lifetime of the contained object is not dependent on the container object.
    • Aggregation is used when objects can be shared or need to exist independently across multiple contexts.
    • It provides loose coupling, flexibility, and allows for shared ownership.
    • Aggregation is appropriate when the part objects can exist without the whole object, as opposed to composition, where the contained objects are tightly bound to the containing object.
    Previous topic 12
    Composition
    Next topic 14
    Inheritance

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,039
      Code examples0
      DifficultyIntermediate