• ### Announcements

#### Archived

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

# Constructor varible initialization?

## 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 on other sites
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 on other sites
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

• ### Forum Statistics

• Total Topics
628281
• Total Posts
2981795

• 10
• 11
• 17
• 14
• 9