C++ Initializer Lists – when and why should be used

C++ Initialization List :

A place in the constructor to initialize the member variables. In the constructor definition, coma separated list of member variables(with initialization values in the brackets) is placed after constructor name followed by  “:”

Code Example :

Initializer list

Regular assignment in the constructor ( inside curly braces)

So how initialization in the initializer list is different from assignments done in the constructor.

As per the C++ rules, constructor starts execution only after all of the member objects/variables are initialized ( not assigned). So when assignments  are done two functions are executed, constructor for that member object  and assignment operator of that object to do the assignment.

While in case of initializer list, only assignment operation will be executed. This is where the efficiency comes to play.  Think about a huge data object having huge memory allocation, it is highly inefficient to do the assignment( calling constructor and then calling assignment operator) as it will go through memory allocation twice from constructor and assignment operator.

  • Initializer List Use :
  1. If a class has const member  or reference to an object, as const or reference can not be assigned multiple times but must be initialized at the place of declaration. However as per C++ rules one cannot initialize member variable inside class declaration, the only way to initialize them is through initializer list
  2. If a class does not have default constructor, then how do you instantiate the object. As assigning the member variable inside the constructor will not work as it needs default constructor to be called first, before assignment. Only way to pass the parameter is to the constructor is through initializer list.

2 thoughts on “C++ Initializer Lists – when and why should be used

  1. How comes in line 14 of the last code block, you wrote …:fc(10),… instead of m_fc(10) ?

Leave a Reply