Object-Oriented Thinking in C++: Object Composition

An object can contain another object. The relationship between the two is called composition.

In Listing 10.11, you defined the BMI class to contain a string data field. The relationship between BMI and string is composition.

Composition is actually a special case of the aggregation relationship. Aggregation models has-a relationships and represents an ownership relationship between two objects. The owner object is called an aggregating object and its class an aggregating class. The subject object is called an aggregated object and its class an aggregated class.

An object may be owned by several other aggregating objects. If an object is exclusively owned by an aggregating object, the relationship between the object and its aggregating object is referred to as composition. For example, “a student has a name” is a composition relation­ship between the Student class and the Name class, whereas “a student has an address” is an aggregation relationship between the Student class and the Address class, since an address may be shared by several students. In UML, a filled diamond is attached to an aggregat­ing class (e.g., Student) to denote the composition relationship with an aggregated class (e.g., Name), and an empty diamond is attached to an aggregating class (e.g., Student) to denote the aggregation relationship with an aggregated class (e.g., Address), as shown in Figure 10.12.

Each class involved in a relationship may specify a multiplicity. A multiplicity could be a number or an interval that specifies how many objects of the class are involved in the relation­ship. The character * means an unlimited number of objects, and the interval m..n means that the number of objects should be between m and n, inclusive. In Figure 10.12, each student has only one address, and each address may be shared by up to three students. Each student has one name, and a name is unique for each student.

An aggregation relationship is usually represented as a data field in the aggregating class. For example, the relationship in Figure 10.12 can be represented as follows:

Aggregation may exist between objects of the same class. For example, a person may have a supervisor. This is illustrated in Figure 10.13.

In the relationship “a person has a supervisor,” as shown in Figure 10.13, a supervisor can be represented as a data field in the Person class, as follows:

class Person {

private:

Person supervisor; // The type for the data is the class itself 

}

If a person may have several supervisors, as shown in Figure 10.14, you may use an array to store supervisors (for example, 10 supervisors).

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *