Program To Illustrate The Order Of Execution In Composition Using C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code


To copy code: Click View Source “View Source” on the right of this code snippet.

Background and Explanation of the code

In this program the objects c1 and c2 of cont1 and cont2 classes respectively are defined as data members of class comp.The statement

comp c3 (30, 20, 10);

creates an object c3 of class comp and invokes its constructor comp (int, int, int) for initializing its data member c and data members a and b of its container objects using respective constructors.From the output it is clear that constructors of the container objects c1 and c2 are executed before the constructor of composite object c3.Moreover the constructor of c1 object is executed before constructor of c2 object as former is declared before the other in the class comp.

The constructor of the composite class comp has the header

comp (int cc, int bb, int aa) : c2 (bb), c1 (aa)

It specifies that cc,bb and aa are the parameters that are to be supplied when an object of comp is created. The total number of arguments passed must be equal to the values to be initialized.The initializer list starting with colon(:) specifies the list of objects along with their arguments which are to be passed enclosed in parentheses.Each object specified must be separated by commas whose purpose is to invoke the respective constructors by passing values specified in parentheses.

The order of execution of destructor is reverse as that of  constructor execution.So the destructor of composite object is executed before the destructor of the object it contains .


Cont1’s single parameter constructor

Cont2’s single parameter constructor

Comp’s constructor with three parameters