Aggregation

Introduction

An aggregation is a specific type of composition where no ownership between the complex object and the subobjects is implied. When an aggregate is destroyed, the subobjects are not destroyed.
In an aggregation, we also add other subclasses to our complex aggregate class as member variables. However, these member variables are typically either references or pointers that are used to point at objects that have been created outside the scope of the class.

Examples

Example 1

#include <string>
using namespace std;
 
class Teacher
{
private:
    string m_strName;
public:
    Teacher(string strName)
        : m_strName(strName)
    {
    }
 
    string GetName() { return m_strName; }
};
 
class Department
{
private:
    Teacher *m_pcTeacher; // This dept holds only one teacher
 
public:
    Department(Teacher *pcTeacher=NULL)
        : m_pcTeacher(pcTeacher)
    {
    }
};
 
int main()
{
    // Create a teacher outside the scope of the Department
    Teacher *pTeacher = new Teacher("Bob"); // create a teacher
    {
        // Create a department and use the constructor parameter to pass
        // the teacher to it.
        Department cDept(pTeacher);
 
    } // cDept goes out of scope here and is destroyed
 
    // pTeacher still exists here because cDept did not destroy it
    delete pTeacher;
}

Differences between composition and aggregation

Compositions:

  • Typically use normal member variables
  • Can use pointer values if the composition class automatically handles allocation/deallocation
  • Responsible for creation/destruction of subclasses

Aggregations:

  • Typically use pointer variables that point to an object that lives outside the scope of the aggregate class.
  • Can use reference values that point to an object that lives outside the scope of the aggregate class
  • Not responsible for creating/destroying subclasses
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.