Constructor varible initialization?

Started by
1 comment, last by DevLiquidKnight 20 years, 3 months ago
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?
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
Use intializer list whenever possible because it''s more efficient. In your example here:

// ThisCMyClass::CMyClass(): var1(0), var2(5.0f), var3(NULL){}vs.   // thisCMyClass::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

This topic is closed to new replies.

Advertisement