Initialization list

In the previous chapter, we learned about how classes and their objects can be created and the different ways their members can be accessed. We also saw how data members are initialized in the constructor of any class as shown below.

An initializer list starts after the constructor name and its parameters and begins with a colon ( : ) followed by the list of variables which are to be initialized separated by a comma with their values in curly brackets.

In this example, the initializer list is directly initializing the variables length and breadth with the values of l and b which are 7 and 4 respectively.

This is the same as the following code with the only difference that in the above example, we are directly initializing the variables while in the following code, the variables are being assigned the parameterized values.

Need for Initialization List

Though we can use initialization list anytime as we did in the above examples, but there are certain cases where we have to use initialization list otherwise the code won't work.

If we declare any variable as const, then that variable can be initialized, but not assigned.

Any variable declared with const keyword before its data type is a const variable.

To initialize a const variable, we use initialization list. Since we are not allowed to assign any value to a const variable, so we cannot assign any value in the body of the constructor. So, this is the case where we need initialization list.

Following is an example initializing a const data member with initialization list.