[C++] Member initialization

Started by
4 comments, last by jrdmellow 12 years, 4 months ago
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! :P
Advertisement
Initialization lists.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

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.

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! :P


Yeah it's called an initialiser list.


Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

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

This topic is closed to new replies.

Advertisement