You must use the member initialization list in the following cases in order for your program to compile:
1. When initializing a reference member
2. When initializing a const member
3. When invoking a base or member class constructor with a set of arguments
4.
The compiler iterates over the initialization list, inserting the initializations in the proper order within the constructor prior to any explicit user code. The order in which the list entries are set down is determined by the declaration order of the members within the class declaration, not the order within the initialization list.
This apparent anomaly between initialization order and order within the initialization list can lead to the following nasty pitfall:
class X
{
int i;
int j;
public:
X(int val):j(val), i(j) {}//Problem!
}
The author recommends always placing the initialization of one member with another (if you really feel it is necessary) within the body of the constructor.
No comments:
Post a Comment