Skip to main content
gamedev.net
🔒 Locked

[C++] Member initialization

Started by jrdmellow Dec 15, 2011 at 6:51 PM 4 replies 1.4k views
Original Post
jrdmellow
jrdmellow
A (hopefully) quick question;

Does this type of initialization have a name?

class MyClass
{
public:

MyClass();
// ...
private:
int m_count;
};

MyClass::MyClass()
: m_count(0) // <-- this guy right here
{
}



Are there any benefits/fallbacks to doing it this way as opposed to this;

MyClass::MyClass()
{
m_count = 0;
}


Thanks!

PS - sorry if this has been posted before, it's hard to find something when you don't know it's name!
WavyVirus
WavyVirus
That is called an "initialization list".

Generally you should prefer using this method to assigning values in the body of the constructor. If you do it in the constructor body, the variable actually has its default constructor called before the constructor body is entered i.e. it is default-constructed and then immediately overwritten in the body of the constructor, which is wasteful (an extra constructor call).

There isn't actually a performance hit when using an int or similar built-in type, but it is still advisable to use the initialization list for the sake of consistency.
NightCreature83
NightCreature83

A (hopefully) quick question;

Does this type of initialization have a name?

class MyClass
{
public:

MyClass();
// ...
private:
int m_count;
};

MyClass::MyClass()
: m_count(0) // <-- this guy right here
{
}



Are there any benefits/fallbacks to doing it this way as opposed to this;

MyClass::MyClass()
{
m_count = 0;
}


Thanks!

PS - sorry if this has been posted before, it's hard to find something when you don't know it's name!


Yeah it's called an initialiser list.


Red Ant
Red Ant
It's also the only way to initialize const members and reference members.
jrdmellow
jrdmellow
Got it. Thanks for the responses guys/gals!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.