Possible Duplicate:
C++ initialization lists
What are the pros/cons of initializing variables at option 1 vs option 2?
class MyClass
{
public:
MyClass( float f, char a );
private:
float mFloat;
char mCharacter;
bool mBoolean;
int mInteger;
};
MyClass::MyClass( float f, char a ) : mFloat( f ), mBoolean( true ) // option 1.
{
// option 2
mCharacter = a;
mInteger = 0;
}
Edit: Why is option 2 so common?
This question is related to
c++
constructor
initialization
In short, always prefer initialization lists when possible. 2 reasons:
If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.
Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.
Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.
Although it doesn't apply to this specific example, Option 1 allows you to initialize member variables of reference type (or const
type, as pointed out below). Option 2 doesn't. In general, Option 1 is the more powerful approach.
There are many other reasons. You should always initialize all member variables in the initialization list if possible.
Option 1 allows you to initialize const
members. This cannot be done with option 2 (as they are assigned to, not initialized).
Why must const members be intialized in the constructor initializer rather than in its body?
See Should my constructors use "initialization lists" or "assignment"?
Briefly: in your specific case, it does not change anything. But:
My guess for why option 2 is more common is that option 1 is not well-known, neither are its advantages. Option 2's syntax feels more natural to the new C++ programmer.
Option 1 allows you to use a place specified exactly for explicitly initializing member variables.
Source: Stackoverflow.com