There are two ways a constructor can initialize member variables. First, it can explicitly assign them values inside the body of the constructor. For example, consider MyClass, shown here, which has two integer data members called numA and numB. These member variables are initialized inside the MyClass constructor.
class MyClass {
int numA;
int numB;
public:
/* Initialize numA and numB inside the MyClass
constructor using normal syntax. */
MyClass(int x, int y) {
numA = x;
numB = y;
}
// ...
};
Assigning initial values to member variables numA and numB inside the constructor, as MyClass does, is a common approach, and is the way that member initialization is accomplished for many classes. However, this approach won't work in all cases. For example, if numA and numB were specified as const, like this,
class MyClass {
const int numA; // const member
const int numB; // const member
then they could not be given values by the MyClass constructor because const variables must be initialized and cannot be assigned values after the fact. Similar problems arise when using reference members, which must be initialized, and when using class members that don't have default constructors. To solve these types of problems, C++ supports a second member initialization syntax, which gives a class member an initial value when an object of the class is created.
The member initialization syntax is similar to that used to call a base class constructor. Here is the general form:
constructor(arg-list) : member1(initializer),
member2(initializer),
// ...
memberN(initializer)
{
// body of constructor
}
The members that you want to initialize are specified in a comma- separated list that goes after the constructor's declaration and before the body of the constructor. Notice the use and placement of the colon. You can mix calls to base class constructors with member initializations in the same list.
Here is MyClass rewritten so that numA and numB are const members that are given values using the member initialization syntax.
class MyClass {
const int numA; // const member
const int numB; // const member
public:
// Initialize using initialization syntax.
MyClass(int x, int y) : numA(x), numB(y) { }
// ...
};
Here, numA is initialized with the value passed in x, and numB is initialized with the value passed in y. Even though numA and numB are now const, they can be given initial values when a MyClass object is created because the member initialization syntax is used.
One last point: Class members are constructed and initialized in the order in which they are declared in a class, not in the order in which their initializers occur.
|