Aggregation
Aggregation also involves a container object that contains another object. The main difference is that in aggregation, the lifetime of the contained object is independent of the lifetime of the container object.
In aggregation, the contained object could be constructed even before the container object is constructed. This is opposite to composition, in which the contained object should have a lifetime shorter than or equal to the container object.
The following example, example 7.2, demonstrates an aggregation relationship. It describes a very simple game scenario in which a player picks up a gun, fires multiple times, and drops the gun.
The player
object would be a container object for a while, and the gun
object would be a contained object as long as the player object holds it. The lifetime of the gun object is independent of the lifetime of the player object.
The following code box shows the header file of the Gun
class:
#ifndef EXTREME_C_EXAMPLES_CHAPTER_7_2_GUN_H...