|
|
|
|
|
|
|
Earlier we said that two classes typically exhibit one of the following relationships: they are independent of each other, they are related by inheritance, or they are related by composition. Composition (or containment) is the relationship in which the internal data of one class A includes an object of another class B. Stated another way, a B object is contained within an A object. |
|
|
|
 |
|
 |
|
|
Composition (Containment) A mechanism by which the internal data (the state) of one class includes an object of another class. |
|
|
|
|
|
|
|
|
C++ does not have (or need) any special language notation for composition. You simply declare an object of one class to be one of the data members of another class. Let's look at an example. |
|
|
|
|
|
|
|
|
Design of a TimeCard Class |
|
|
|
|
|
|
|
|
You are developing a program to manage a factory's payroll. Employees are issued time cards containing their ID numbers. When reporting for work, an employee punches in by inserting the card into a clock, which punches the current time onto the card. When leaving work, the employee takes a new card and punches out to record the departure time. For your program, you decide that you need a TimeCard ADT to represent an employee's time card. The abstract data consist of an ID number and a time. The abstract operations include Punch the Time, Print the Time Card Data, constructor operations, and others. To implement the ADT, you must choose a concrete data representation for the abstract data and you must implement the operations. Assuming an employee ID number is a large integer value, you choose the long data type to represent the ID number. To represent time, you remember that one of your friends has already written and debugged a Time class (we'll use the one from earlier in this chapter). At this point, you create a TimeCard class declaration as follows: |
|
|
|
|
|
|
|
|
#include time.h
.
.
.
class TimeCard
{
|
|
|
|
|
|