Search

10.3 — Aggregation

In the previous lesson on Composition, we noted that object composition is the process of creating complex objects from simpler one. We also talked about one type of object composition, called composition. In a composition relationship, the whole object is responsible for the existence of the part.

In this lesson, we’ll take a look at the other subtype of object composition, called aggregation.

Aggregation

To quality as an aggregation, a whole object and its parts must have the following relationship:

  • The part (member) is part of the object (class)
  • The part (member) can belong to more than one object (class) at a time
  • The part (member) does not have its existence managed by the object (class)
  • The part (member) does not know about the existence of the object (class)

Like a composition, an aggregation is still a part-whole relationship, where the parts are contained within the whole, and it is a unidirectional relationship. However, unlike a composition, parts can belong to more than one object at a time, and the whole object is not responsible for the existence and lifespan of the parts. When an aggregation is created, the aggregation is not responsible for creating the parts. When an aggregation is destroyed, the aggregation is not responsible for destroying the parts.

For example, consider the relationship between a person and their home address. In this example, for simplicity, we’ll say every person has an address. However, that address can belong to more than one person at a time: for example, to both you and your roommate or significant other. However, that address isn’t managed by the person -- the address probably existed before the person got there, and will exist after the person is gone. Additionally, a person knows what address they live at, but the addresses don’t know what people live there. Therefore, this is an aggregate relationship.

Alternatively, consider a car and an engine. A car engine is part of the car. And although the engine belongs to the car, it can belong to other things as well, like the person who owns the car. The car is not responsible for the creation or destruction of the engine. And while the car knows it has an engine (it has to in order to get anywhere) the engine doesn’t know it’s part of the car.

When it comes to modeling physical objects, the use of the term “destroyed” can be a little dicey. One might argue, “If a meteor fell out of the sky and crushed the car, wouldn’t the car parts all be destroyed too?” Yes, of course. But that’s the fault of the meteor. The important point is that the car is not responsible for destruction of its parts (but an external force might be).

We can say that aggregation models “has-a” relationships (a department has teachers, the car has an engine).

Similar to a composition, the parts of an aggregation can be singular or multiplicative.

Implementing aggregations

Because aggregations are similar to compositions in that they are both part-whole relationships, they are implemented almost identically, and the difference between them is mostly semantic. In a composition, we typically add our parts to the composition using either normal member variables (or pointers where the allocation and deallocation process is handled by the composition class).

In an aggregation, we also add parts 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. Consequently, an aggregation usually either takes the objects it is going to point to as constructor parameters, or it begins empty and the subobjects are added later via access functions or operators.

Because these parts exist outside of the scope of the class, when the class is destroyed, the pointer or reference member variable will be destroyed (but not deleted). Consequently, the parts themselves will still exist.

Let’s take a look at a Teacher and Department example in more detail. In this example, we’re going to make a couple of simplifications: First, the department will only hold one teacher. Second, the teacher will be unaware of what department they’re part of.

In this case, teacher is created independently of dept, and then passed into dept’s constructor. When dept is destroyed, the m_teacher pointer is destroyed, but the teacher itself is not deleted, so it still exists until it is independently destroyed later in main().

Pick the right relationship for what you’re modeling

Although it might seem a little silly in the above example that the Teacher’s don’t know what Department they’re working for, that may be totally fine in the context of a given program. When you’re determining what kind of relationship to implement, implement the simplest relationship that meets your needs, not the one that seems like it would fit best in a real-life context.

For example, if you’re writing a body shop simulator, you may want to implement a car and engine as an aggregation, so the engine can be removed and put on a shelf somewhere for later. However, if you’re writing a racing simulation, you may want to implement a car and an engine as a composition, since the engine will never exist outside of the car in that context.

Rule: Implement the simplest relationship type that meets the needs of your program, not what seems right in real-life.

Summarizing 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 parts

Aggregations:

  • Typically use pointer or reference members that point to or reference objects that lives outside the scope of the aggregate class
  • Not responsible for creating/destroying parts

It is worth noting that the concepts of composition and aggregation are not mutually exclusive, and can be mixed freely within the same class. It is entirely possible to write a class that is responsible for the creation/destruction of some parts but not others. For example, our Department class could have a name and a Teacher. The name would probably be added to the Department by composition, and would be created and destroyed with the Department. On the other hand, the Teacher would be added to the department by aggregation, and created/destroyed independently.

While aggregations can be extremely useful, they are also potentially more dangerous. Because aggregations do not handle deallocation of their parts, that is left up to an external party to do so. If the external party no longer has a pointer or reference to the abandoned parts, or if it simply forgets to do the cleanup (assuming the class will handle that), then memory will be leaked.

For this reason, compositions should be favored over aggregations.

A few warnings/errata

For a variety of historical and contextual reasons, unlike a composition, the definition of an aggregation is not precise -- so you may see other reference material define it differently from the way we do. That’s fine, just be aware.

One final note: In the lesson Structs, we defined an aggregate data types (such as structs and classes) as a data types that groups multiple variables together. You may also run across the term “aggregate class” in your C++ journeys, which is defined as a struct or class that has only default constructors/destructors, no protected or private members, and no inheritance or virtual functions -- essentially a plain-old-data struct. Despite the similarities in naming, aggregates and aggregation are different and should not be confused.

Quiz time

1) Would you be more likely to implement the following as a composition or an aggregation?
1a) A ball that has a color
1b) A employer containing multiple employees
1c) The departments in a university
1d) Your age
1e) A bag of marbles

Show Solution

2) Update the Teacher/Dept example so the Dept can handle multiple Teachers. The following code should execute:

This should print:

Department: Bob Frank Beth
Bob still exists!
Frank still exists!
Beth still exists!

Hint: Use a std::vector to hold the teachers. Use the std::vector::push_back() to add Teachers. Use the std::vector::size() to get the length of the std::vector for printing.

Show Solution

10.4 -- Association
Index
10.2 -- Composition

34 comments to 10.3 — Aggregation

  • Stuart

    Alex, I don’t understand why the pointer pcTeacher is assigned NULL as a Department constructor parameter, because it assigns to the address of the pTeacher pointer when an object of Department is instantiated. It seems like it’s never a null pointer. (?)

    • It’s assigned NULL as a default parameter just in case the programmer wants to create a department with no teacher. For example:

      In this case cDept would call the Department constructor with pcTeacher set to NULL. This NULL value would then be assigned to cDept.m_pcTeacher by the constructor.

  • Prateek Jain

    How do you handle the situation when subclass object gets destroyed? In our case, if the teacher dies for some reason (say heart attack:-) in case of real world situation), the pTeacher pointer will still have some value but that value will no longer be valid. If Department class has some member which access pTeacher, this could give rise to some potential problem.
    If you somehow can pass a message to Department class, it can make pTeacher equal to NULL but checking (pTeacher == NULL) everywhere in Department class doesn’t seem to be a good idea.
    How do you incorporate it into your design?

    • Alex

      Great question. In real life, if a teacher died, someone would need to notify the department so they could remove the teacher from the roster.

      In C++-land, it’s better to do things the other way around: Before you kill an object, make sure that all pointers or references to it are removed, and then kill it (killing something should always be the last step). In terms of aggregations, this likely means writing a function to set the appropriate child to null. In cases where the aggregate has a single instance of the object and you know what it is, you can just use an access function to set the value to null (e.g. setTeacher(nullptr)).

      In a more complex aggregation (e.g. a Department that can hold multiple Teachers), you’ll probably need to write a remove() function and pass in the specific Teacher to remove as an argument so it knows which of the multiple teachers you want to remove.

      You should check if teacher == nullptr everywhere inside your Department, because this is a valid state for Department.

  • shouldn’t

    return 0?

  • f117f117f117677

    Hi: Alex
    as you said
    there are two pointers point to Teacher(“Bob”). pTeacher and m_pcTeacher

    if aggregate class is destroyed then m_pcTeacher is destroyed. So
    teacher(“Bob”) is gone(died).

    but delete pTeacher again? is this problem? pTeacher become a wild pointer?

  • serenity

    f117f117f117677: “class Department” doesn’t actaully delete the teacher; the only thing removed when it’s destroyed is its pointer to the teacher. The pointer in main() remains and is still valid, so there is no wild pointer and no double delete.

  • auasp

    the heading of this lesson is Aggregration.
    (one extra r)

  • Amit

    Thanks for teh description but there are couple of loose ends:
    1. How is association different from aggregation and composition ? You may want to add a section on that
    2. If a class has a data member(only one) which points to another object but this is not allocated/dealloacted in constructor and destructor. Will this be aggregation or composition ? For teh relation to be aggregation is it necessary that you should have more that one object of the same type ?

  • hector

    I love the new look of the site yo 🙂

  • mccp13

    I still don’t get the pointer *m_pcTeacher. when m_pcTeacher recieves pTeacher, it means that m_pTeacher and pTeacher are pointing to the same address. So when m_pcTeacher is destroyed doesn’t that mean that the address to which it is pointing to is freed, so when pTeacher gets the contents of the address, it could have changed since it is already free and ready to be used by some other program…???

    • Alex

      When dept is destroyed, the m_teacher member pointer is destroyed, but it is not deleted (that is, the contents that it was pointing to are still valid)

  • maxatan

    Hi ! and congratulations for your job !

    However, I have a question : What would be the code with more than one teacher belonging to the Department ? How will you implement it ? With a list of pointers to Teachers (list) ?

    Thank you in advance for your advice

  • Darin

    Hi Alex,
    I want to ask how do you dereference something like
    Teacher *pTeacher = new Teacher(“Bob”);
    since I could not fully inderstand the whole aggregration example. The only thing that I was able to understande was that the classes are exchanging the adress that pTeacher holds, but I cannot actually do anything with it(since I cannot dereference it). If possible could you please explain?

  • Kiran C K

    In the above code,  doesn’t it cause memory leak if more and more Department objects are created?

    • Alex

      No. Departments don’t dynamically create or delete any memory. They can just optionally hold a Teacher object while they exist.

      We would have a memory leak if we didn’t delete the Teacher ourselves (in this case, in main()), since Department won’t do that for us.

      • Kiran C K

        Got that, Alex. Thanks. What misguided me was the comment in the example :

        cDept went out of scope and in the following line, pTeacher is deallocated. I misunderstood it as even if pTeacher, which is a teacher object is deallocated, it still exists as a cDept object.

        Also, cDept did not allocate any memory for pTeacher, so there is no need for cDept to destroy it, right?

        • Alex

          Right. When cDept goes out of scope, it doesn’t destroy the Teacher because it didn’t allocate it.

          Since some external party dynamically allocated Teacher, it’s up to that external party to delete it.

  • SUDARSHAN KOLAR

    Hi Alex…

    Can you please explain this part of the code:

    Teacher *pTeacher = new Teacher("Bob");

    Especially, Teacher("Bob");

    Can you please link where you discussed it?

    Thanks for great materials …

    • Alex

      Teacher(“Bob”) instantiates an object of type Teacher using a constructor that takes a parameter of type const char*.

      It’s the class equivalent of something like: int *ptr = new int(5);

      If you’re having trouble with this, re-review chapters 6.9 -- Dynamic memory allocation with new and delete, 8.5 -- Constructors, and 8.14 -- Anonymous variables and objects.

  • Nima

    Greetings dear Alex.
    Thank you for your great tutorials.
    I search about relationship between classes in C++ and see many of it.
    each site introduce just some part of relationship and I am really confuse.
    I follow your tutorials and see your explanations for composition and aggregation but what about Association, reflective Association, Realization, Generalization, Implementation, Dependency, Multiplicity and many more?
    Can you help me out?
    Best regards.

    • Alex

      I’m just starting to rewrite the lessons for Composition and Aggregation, and am planning on adding a new lesson on Association. I’ll undoubtedly add mentions of the other types of relationships as I progress. Generalization is already covered under the chapters on inheritance, and implementation under the chapters on abstract base classes. Dependencies and multiplicities hopefully are obvious.

      What is a reflective association?

  • Nima

    Sorry dear Alex.
    I’m  wrong.
    Actually it is reflexive association.
    see this:
    http://cruise.eecs.uottawa.ca/umple/ReflexiveAssociations.html
    Cheers.

  • Nima

    Hello again dear Alex.
    I forget to tell you that have you an article about UMLs too? UMLs for all class relationships in C++ programming?
    Best regards.

    • Alex

      Nope. UML is great for drawing class diagrams, but not strictly related to C++ (more to general programming). It’s a great topic though, just not one I intend to cover as part of this tutorial series.

  • Ryan

    In question 2 on the quiz, you say that the "following code should execute"… And on line 16, I find the statement: "dept.remove(t2);". However, the solution omits this statement. Is this a typo? I am having trouble creating a function that can remove a teacher. Thanks!

    • Alex

      I’ve removed the dept.remove(t2) line from the sample. I was originally going to include the ability to remove teachers as well (seems obvious, doesn’t it?) but it turns out that in order to remove something from a std::vector, we need to cover a topic we haven’t covered yet (iterators). I’m currently trying to decide whether I should add an introduction to iterators lesson later in this chapter.

  • Pranay

    Hello Alex,
    Can we consider aggregation as an substitute of friend function ?

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter