Possible Duplicate:
Benefits of Initialization lists
I’ve been learning C++ for the past few days now and I’m seeing two formats where I can’t determine advantages/disadvantages of the two. Hope someone can help me here.
The first one has variables being initialized with var(value)
class Foo
{
public:
Foo(): itsVar1(2), itsVar2(345){}
private:
int itsVar1;
int itsVar2;
};
The second is initialized with the assignment operator var = value.
class Foo
{
public:
Foo()
{
itsVar1 = 2;
itsVar2 = 345;
}
private:
int itsVar1;
int itsVar2;
};
Is there an advantage to one over the other? Is it personal preference?
The first style(?) looks more confusing to me. It looks like you’re calling a method and passing in that value. Looks very implicit; whereas, the second is very explicit and as someone coming from Python “explicit is better than implicit” I prefer the second method. What am I missing?
Always use initializer lists (the first style) whenever you can. The major good reasons for doing so are:
Not using initializer lists makes it harder to guarantee exception safety. Using RAII classes for your class member variables, along with initializer lists, makes it trivial to guarantee that your constructors won’t leak resources when faced with exceptions thrown by the constructors of the member variables.
Assignments are no better performing than initializer lists. If the member variable types are nontrivial, the assignments will perform worse in fact. With initializers, member variables will be constructed in place and there will be no default construction happening. Using assignments lets all the member variables become default constructed first.
Initializer lists are the only way to assign values to reference and const member variables.