Advertisement

member variable initialization in the header...or not? :S

Started by July 18, 2017 08:03 AM
11 comments, last by MarcusAseth 7 years, 4 months ago
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.)

Hello to all my stalkers.

Thanks for stressing this point Lactose, I dind't had realized that. :/

Fortunately  it never happened to me so far and I'm going to pay attention to it from now on

This topic is closed to new replies.

Advertisement