In the early versions of C++, class members were initialized inside the constructor through assignment. Later, the ability to initialize class members before entering the constructor body using an initializer list became available, which is critically important for constant members, references, and performance.
Some class members (e.g., const fields or references) cannot be initialized through assignment inside the constructor body—they must be set at the moment of creation. Moreover, if assignment is used, the default constructor will be called first, followed by assignment (two actions), which can be costly for complex objects:
class Example { const int x; std::string str; public: Example(int val, const std::string& s) : x(val), str(s) {} };
Use the initializer list to initialize class members immediately. This is especially important for const, references, member classes without a default constructor, and for performance when working with STL classes and large structures.
Code example:
class Point { const int x; int& y; public: Point(int val, int& ref) : x(val), y(ref) {} };
Key features:
Can the order of initialization of class members be changed through the order in the constructor's initializer list?
No! Members are always initialized in the order they are declared in the class, not by the order in the initializer list. Ignoring this rule leads to initialization order errors.
What happens if a reference member is not initialized in the initializer list but only in the constructor body?
Compilation error! References, like const fields, can only be initialized in the initializer list—they must receive a value before entering the constructor body.
After initializing a const member in the initializer list, can it be changed in the constructor body?
No, a constant member cannot be changed after initialization—attempting to change such a field will result in a compilation error.
In the constructor, the class member is initialized inside the constructor body. For complex objects, resources are spent on calling the default constructor, then on assignment, and finally on destroying the temporary object.
Pros:
Cons:
All members are initialized immediately in the initializer list, with no unnecessary operations or issues with immutable fields.
Pros:
Cons: