Aggregation / Composition: Objects as Class Members

Timer class example:

This example contains two classes -- Display and Timer. You can access the code here.

The files are:


Note the relationship between the classes.  Two Display objects are used as member data in the Timer class declaration -- they are named hours and minutes (these are variables).

 class Timer 
 { 
 public: 
    // public member functions 
 private: 
    // Display objects declared as private data of a Timer object 
    Display hours, minutes; 
 }; 

This is the "has-a" relationship -- a Timer object "has" two objects of type Display embedded inside of it, as components.

Always pay attention to context, including who is the intented "user" of any given class. In the case of aggregation, the containing class is the "user" of the embedded objects.

Constructors for embedded objects


Another example of classes in a "has-a" relationship:
SodaMachine class

We will see many examples of composition/aggregation in the future. It's a very common relationship to use in class design.