An AlarmClock object needs to know when it is supposed to sound its alarm, so why not include a Time object as a member of the AlarmClock class? Such a capability is called composition.
- Composition; Class has objects of other classes as members
- Construction of objects; Member objects constructed in order declared
- Not in order of constructor's member initializer list
- Constructed before enclosing class objects (host objects)
The program of Figs. 9-14 uses class Date and class Employee to demonstrate objects as members of other objects. The colon (:) in the header separates the member initializers from the parameter list. In Fig. 14, when each of the Employee's Date member object's initialized in the Employee constructor's member initializer list, the default copy constructor for class Date is called. This constructor is defined implicitly by the compiler and does not contain any output statements.
Figure 9:
Date class definition.
|
Figure 10:
Date class member-function definitions. (part 1 of 2)
|
Figure 11:
Date class member-function definitions. (part 2 of 2)
|
Figure 12:
Employee class definition showing composition.
|
Figure 13:
Employee class member-function definitions,including constructor with a member-initializer list.
|
Figure 14:
Member-object initializers.
|
2004-07-05