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

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:

// This example states the order of constructor and destructor call
// of composed objects including main class.

#include
using namespace std;

class Battery{

public:
	Battery(){cout<<"Constructor: Including Battery\n";}
	~Battery(){cout<<"Destructor : Removing Battery\n";}
};

class Sim{

public:

	Sim(){cout<<"Constructor: Including Sim\n";}
	~Sim(){cout<<"Destructor : Removing Sim\n";}
};

//Main class composed of Battery and Sim class
class Mobile{

private:	
	Battery _battery;//composed object
	Sim _sim;        // composed object

public:
	Mobile(){cout<<"Constructor: Mobile is assembled and ready to use!!!\n";}	
	~Mobile(){cout<<"Destructor : Dissembling Mobile\n";}
};

//--------------------TEST--------------------------------------

int main()
{
	Mobile device; // create the object that will call required constructors
	

	return 0;
}

OUTPUT

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

Related Posts