
Order of Member Initialization
One of the most common tasks a constructor carries out is initializing data members. In the Number class the constructor must initialize the count data member to 0. You might think that this would be done in the constructor's function body, like this:
Number ( )
{
count = 0 ;
}
However, this is not the preferred approach ( although it does work ). Here's how you should initialize a data member:
Number ( ) : count ( 0 )
{ }
The initialization takes place following the member function declarator but before the function body. It's preceded by a colon. The value is placed in parentheses following the data member.
If multiple members must be initialized, they're separated by commas.
class Employee
{
long ssn ;
double salary ;
public :
Employee ( long n, double s ) : salary ( s ), ssn ( n )
{ }
// . . .
} ;
Since the initialization of one class data member may be dependent upon the initialization of another member, it's important to know the order in which the members get initialized. Members are initialized in the declaration order.
For example, in the above Employee class the data member ssn is guaranteed to be initialized before salary because it appears first.