Search code examples
c++classinitializationdata-members

When to use which data member initialization in C++


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:

  1. using a member initializer list
  2. using the Constructor
  3. using a declaration in the class body

When to use which?


Solution

  • 1: Using a declaration in the class body

    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.

    2: Using a member initializer list

    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.

    3: Using the constructor body

    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.