Scenarios where you have to use member initialization list in C++
1. When initialize a reference member
2. When initialize a const member
3. When call a base class's constructor that requires a group of parameters
4. When call a member class's constructor that requires a group of parameters
Member initialization list is preferred to the initialization inside the constructor. The following is one example:
private:
String myName;
public:
Constructor()
{
myName = 0
........
}
In this case, a temp object will be created for 0, and copy that to myName, and finally destroy the temp object.
A revised approach is:
Constructor(): myName(0)
Two points are important to remember about the initialization list's operation
1) It happens before any explicit users code;
2) Its operating sequence is determined by the declaration sequence of those members in the class declaration, instead of their seen order found in the initialization list.
2. When initialize a const member
3. When call a base class's constructor that requires a group of parameters
4. When call a member class's constructor that requires a group of parameters
Member initialization list is preferred to the initialization inside the constructor. The following is one example:
private:
String myName;
public:
Constructor()
{
myName = 0
........
}
In this case, a temp object will be created for 0, and copy that to myName, and finally destroy the temp object.
A revised approach is:
Constructor(): myName(0)
Two points are important to remember about the initialization list's operation
1) It happens before any explicit users code;
2) Its operating sequence is determined by the declaration sequence of those members in the class declaration, instead of their seen order found in the initialization list.
Labels: C++, Member initialization list
