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

(Last Updated On: August 14, 2015)

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.




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.