Friday, February 23, 2007

C++ - Initialization Lists

Constructing an object consists of two parts:
  1. Creating the object
    • Without initialization list: Assign default values to the object's member variables
    • With initialization list: Assign specified values in initialization list to member variables
  2. Running the constructor's body
In object creation without an initialization list, default values are assigned to the object's member data. If assignments exist inside the body of the constructor, member data will be assigned again. However, with an initialization list, specified values can be assigned in step 1 to avoid assignments in the constructor's body.

Warning: there is no guarantee on the order of assignments (see example).

Before:
MyClass::MyClass()
{
member1 = 1;
member2 = 2;
member3 = member2;
}

After:
MyClass::MyClass()
: member1(1),
member2(2)
//, member3(member2) // No guarantee member2
// was set before here
{
member3 = member2; // need to assign here
}

No comments: