Jump to content

  • Log In with Google      Sign In   
  • Create Account


[C++] Member initialization


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
5 replies to this topic

#1 jrdmellow   Members   -  Reputation: 118

Like
0Likes
Like

Posted 15 December 2011 - 12:51 PM

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
Jordan M. www.jordanmellow.com

Sponsor:

#2 ApochPiQ   Moderators   -  Reputation: 14102

Like
0Likes
Like

Posted 15 December 2011 - 01:00 PM

Initialization lists.

#3 WavyVirus   Members   -  Reputation: 735

Like
0Likes
Like

Posted 15 December 2011 - 01:05 PM

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.

#4 NightCreature83   Crossbones+   -  Reputation: 2650

Like
0Likes
Like

Posted 15 December 2011 - 01:05 PM

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, Mad Max

#5 Red Ant   Members   -  Reputation: 447

Like
1Likes
Like

Posted 16 December 2011 - 05:56 PM

It's also the only way to initialize const members and reference members.

#6 jrdmellow   Members   -  Reputation: 118

Like
0Likes
Like

Posted 16 December 2011 - 08:28 PM

Got it. Thanks for the responses guys/gals!
Jordan M. www.jordanmellow.com




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS