Initializer list in C++
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon.
Why using initializer list:
- For initialization of non-static const data members
- For initialization of reference members
- For initialization of member objects which do not have default constructor
- For initialization of base class members
- When constructor's parameter name is same as data member: can be solved with “this->”
Code Example
Explanation
In this example, we have:
- A ParentClass with an integer member x.
- A SubClass with an integer member x.
- A ChildClass that inherits from ParentClass and contains several members, including constant and reference members, a member object, and its own integer members x and y.
- The ChildClass constructor uses an initializer list to initialize its members and the base class.
ChildClass(int constMember, int& referenceMember, int subClassX, int parentClassX, int x, int y) : constMember(constMember), // 1. non-static constant member referenceMember(referenceMember), // 2. reference memeber subObj(subClassX), // 3. member objects that do no have default constructor ParentClass(parentClassX), // 4. base class that does not have default constructor x(x) // 5. [optional] input parameter name == memember name; avoid using "->" { this->y = y; // input parameter name == memember name, use "->" for member variable }
- constMember(constMember): needed to initialize a non-static constant member
- referenceMember(referenceMember): needed to initialize a reference memeber
- subObj(subClassX): needed to initialize a member object that does no have default constructor
- ParentClass(parentClassX): needed to initialize the base class that does not have default constructor
- x(x): [optional] because input parameter name is same as memember variable name, "this->" can be avoided in initializer list
- this->y = y: in contrast, y needs to use "this->" to distinguish between input and member variable.
Conclusion
Initializer list in class constructor is powerful, efficient, and sometimes a must. Recommendation is to always use it whenever possible.