what is order of constructor call for composed objects in a class?

(Last Updated On: March 17, 2018)

Answer: Order of constructor call for composed objects in a class would be as below. Consider an example of Mobile class, composed of Battery and Sim class.

  • Constructor call of composed objects  will be as in order they have declared.
  • Then constructor of main class will be called.

In below example, first Battery class object and then Sim class object have been composed in the main class Mobile. Hence, order of constructor call would be of Battery, Sim and then Mobile. And the destructors will be in reverse order.

C++ Code Example:


                Constructor: Including Battery
                Constructor: Including Sim
                Constructor: Mobile is assembled and ready to use!!!
                Destructor : Dissembling Mobile
                Destructor : Removing Sim
                Destructor : Removing Battery