top of page

Composition

 

A class can contain objects of other classes as members. This is called composition. Composition has a  HAS-A relation with its member objects where as inheritance is having IS-A relationship with its base class.

Here Line class has two members p1 and p2 which are objects of Point class. So line class has members of Point class members twice.

In this case to access x and y of Point, we have to use dot operator twice. If we define a line object as

   Line l1;

then, to access getx() (not shown above) function of first point of l1, we must use

    float a = l1.p1.getx();

 

A container class can access only public methods of its member objects. It can not access protected member and it certainly can not access private members of its member classes.

 

When a constructor is called of container object, first constructors of all member objects are called, then the constructor of container class is called. But when destructor of an object is called, first destructor of container class is called, next destructors of all member objects are called.

In the above example, Line class has two member objects of class Point, p1 and p2. When Line object is created  it calls constructor of Line class which in turn calls constructor of Point class for p1 and for p2 . When main exits, l1 is destroyed which calls its destructor, which calls destructor for p1 and p2. Note that Point class has a one constructor which itself is also default constructor (it has default values for all parameters.

So the output of the program is

Point constructor with 0 0 Point constructor with 0 0 Line default constructor Line destructor Point destructor with 00 Point destructor with 00

Similar to inheritance, implicit calling of member object constructor, requires  member class to have a default constructor. If member class does not have default constructor, then member object must be initialized using constructor explicitly in member initializer list of container class constructor.

Let us modify our previous program and remove default constructor of Point class. Now we need to explicitly call constructors of p1 and p2 in constructor initializer list of Line class as shown below.

When Line object is created with parameters 10,10,30,30, it calls constructor of Line class which in turn calls constructor of Point class for p1 with 10 and 10 and for p2 with 30,30. When main exits, l1 is destroyed which calls its destructor, which calls destructor for p1 and p2.

The output of the program will be

Point constructor with 10 10 Point constructor with 30 30 Line constructed with10103030 Line destructor Point destructor with 3030 Point destructor with 1010

​​​

In the above example, Point class has no default constructor, That is the reason, we are explicitly calling constructors for p1 and p2 in the member initializer list of Line constructor.

bottom of page