In what situations initialization list is must and assignment in constructor body does not help?

Answer: Here is the some of the scenarios where we must use initialization list in C++.

Scenario-1: initialization of constant & reference data member of a class.

In C++, constant or reference data member variables of a class can only be initialized in the initialization list, not using assignment in constructor body.

Both constant and reference data member variables have property that they both must be initialized at the moment of declaration. So, there is only way to use initialization list in constructor, as initialization list initializes class member variables at the time of declaration whereas assignment if constructor body initializes data members after declaration.

Note that if you initialize constant and reference variable in constructor body using assignment operator, compiler will flash an error.

Example:

class Diamond{

private:
	const int a;//constant variable
	int &b; //reference
	
public:
	//initialize const and reference variable in initialization list.
	Diamond( int i, int j, int k):a(i),b(j) //initialization list.
	{
		//Construcotor body	
		//compiler flashes error on initializing const and reference variable here.
		a=5;// error
		b=5;// error
	} 
};

Scenario-2: Initialization of base class data members from derive class.

In this example, Jewellery is the base class and Diamond is the derived class. We’ll be initializing base class variable using derived class object via initialization list.

#include
using namespace std;

enum type{
	BASIC,
	CLASSIC
};

class Jewellery{
	int design;
public:
	Jewellery(int type):design(type)
	{
		 cout << "Jewellery's Constructor called\n";
		 cout << "Design Type :"<<design<<"\n";
	}
};

class Diamond:public Jewellery{

public:
	Diamond( int type):Jewellery(type) //initialization list.
	{		
		 cout << "Diamond's Constructor called\n";

	} 
};

int main(){
		
	Diamond db(BASIC);
	Diamond dc(CLASSIC);

	return 0;
}

Related Posts