Jump to content
  • Advertisement
Sign in to follow this  
PixelStation

[C++] Member initialization

This topic is 2557 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites

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.


Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!