Considering this program:
#include <iostream>
class C
{
public:
C(void): a(1)
{ a=2; }
int a{3};
};
int main(void)
{
C c{};
std::cout << c.a; // 2
}
I can see three forms of data member initialization:
- using a member initializer list
- using the Constructor
- using a declaration in the class body
When to use which?
You should use this when the member will always be initialized with the same value, and it doesn't make sense to have to explicitly write that for each constructor.
The member initializer list is obviously necessary for a member that lacks a default constructor, but aside from that, if you're initializing a member based on the constructor, it makes sense to do it here.
The constructor body is more useful for logic that can't be performed in a single statement (in the init-list). However, I don't think there is much difference between initializing a POD in the member initializer list or the constructor body.