Skip to main content
GameDev.net gamedev.net
🔒 Locked

Constructor varible initialization?

Started by DevLiquidKnight Jan 23, 2004 at 3:18 PM 1 replies 200+ views
Original Post
DevLiquidKnight
DevLiquidKnight
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?
Sneftel
Sneftel
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
simba
simba
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

Topic Locked

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

Sign in to reply to this topic.