Aggregation
Good OO design and implemenation focus on
code reuse. How can/should code be designed
and implemented so that existing code can be
reused without modification? That's one of
the strengths of OO languages like C++.
Aggregation (aka composition)
is a common technique for code reuse. Simply put, aggregation
is using one class as a data member of another class.
This technique is used when the classes have a "has a" relationship.
Consider this simple example.
Recall our now familiar DayOfYear class.
Here's how it might be used in a new class.
Note that a Vactation "has a" DayOfYear.
Also note the following about the code
- The Vacation constructor uses the initialization list
to call the DayOfYear constructor. If it did not do so,
then DayOfYear's default constructor would be automatically
be called.
- In this case, the Vacation class is a USER of the DayOfYear
class and is therefore limited to using DayOfYear's public methods.
- Note that in some cases, the methods of the Vacation class
simply call a method of the DayOfYear class. A classic example
of code reuse.
- Note the return type of Vacation::GetDayOfYear.
Returning by reference to const prevents copying of the
DayOfYear object and does not allow the user to change
Vacation's private data (m_startDOY) by using the reference.
More on this in class.
and here's the impmlementation of the Vacation class
from Vacation.cpp. The usual checking of pre-conditions is
removed so that we can focus on the aggregation aspects of
the code.
Keeping perspective
When multiple classes are involved in a design as in this
case, it's important to keep the proper perspective when
implementing these classes.
As mentioned above, Vaction is a USER of the DayOfYear class
and is limited to using DayOfYear's public methods.
Vaction has no special privileges or permission which allow it
to access the private data members of the DayOfYear class.
It's also important to remember that the DayOfYear class
has no "knowledge" of how it's being used. There should be
no new methods or coded added to the DayOfYear class that
are in anyway specific to Vacation.
It's important that "boundaries" between classes (what each
class knows and doesn't know about the others) not be breached.