3 hours ago, frob said:Be certain they are in the same order as they exist in the class.
Just quoting this for emphasis.
Initialization will happen in the order they are listed in the class, even if you write them in a different order in the initializer list. This can lead to some quite frustrating bugs if you aren't expecting it.
The following example will not have the expected behavior:
class Character
{
public:
Character(int health);
private:
int currentHealth;
int maxHealth;
};
Character::Character(int health) : maxHealth(health), currentHealth(maxHealth)
{
}
The reason being that currentHealth(maxHealth) will happen first (due to currentHealth being listed first in the class), even though it is listed last in the initializer list.
Instead, you would want the following code:
class Character
{
public:
Character(int health);
private:
int currentHealth;
int maxHealth;
};
Character::Character(int health) : currentHealth(health), maxHealth(currentHealth)
{
}
(Alternatively, you could also simply swap the order of the class members currentHealth and maxHealth in the first example.)