DasBoot DasBoot - 1 month ago 15
C++ Question

C++ Initialising fields directly vs initialisation list in default constructor

I'd like to know if there is a difference between this code:

class Foo{
private:
int a = 0;
public:
Foo(){}
}


And:

class Foo{
private:
int a;
public:
Foo(): a(0) {}
}


And, if so, which should be preferred?
I know it's preferable to use an initialiser list than assigning in the constructor body, but what about initialiser list vs directly initialising in field declaration (for primitive types, at least, as is the case here)?

Also, what of the case below:

class Foo{
private:
int a = 0;
public:
Foo(){}
Foo(int i): a(i) {}
}


When the non-default constructor is called: is "a" initialised twice, first to 0 then to "i", or directly to "i"?

Answer

From cppreference - Non-static data members

Member initialization
1) In the member initializer list of the constructor.
2) Through a default member initializer, which is simply a brace or equals initializer included in the member declaration, which is used if the member is omitted in the member initializer list.

If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.