Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

DevLiquidKnight

Constructor varible initialization?

This topic is 5322 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

I was wondering when to use 2 each method of defining varaibles in the constructor of a class and which one is used when? Im not to sure, exactly of why you would use one over the other.. basically what im taking about is this:
// This

CMyClass::CMyClass()
: var1(0), var2(5.0f), var3(NULL)
{
}
vs.
// this

CMyClass::CMyClass()
{
var1 = 0;
var2 = 5.0f;
var3 = NULL;
}
When do I use one over the other or does it matter?

Share this post


Link to post
Share on other sites
Advertisement
Initialize variables in the initializer list whenever possible. Times when it may not be possible:

* when the initialization depends on a complex sequence of code, such as conditionals

* when the initialization depends on calling a virtual function

* when a parent class'' initialization depends on the child class having been initialized


"Sneftel is correct, if rather vulgar." --Flarelocke

Share this post


Link to post
Share on other sites
Use intializer list whenever possible because it''s more efficient. In your example here:


// This

CMyClass::CMyClass()
: var1(0), var2(5.0f), var3(NULL)
{
}

vs.

// this

CMyClass::CMyClass()
{
var1 = 0;
var2 = 5.0f;
var3 = NULL;
}


in the second case the compiler has to insert code to first call the constructor on each of you variables, then create a temporary variable for the constants, invoke the assignment operator and then destroy the temporary variables. Where as in the first example the compiler only needs to invoke the copy constructor. Also, in certain cases you have to use intializer list:

1. When initializing reference variables
2. When initializing const members
3. When invoking base/member class contructors with a set of arguments

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

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

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!