When to use which data member initialization in C++

105 views Asked by At

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?

2

There are 2 answers

0
Weak to Enuma Elish On BEST ANSWER

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.

0
R Sahu On

My suggestion is to use:

int a{3};

This makes sure that a is initialized to 3 no matter how many constructors you have in the class.

My second choice will be to use the member initialization list.

c(void) : a(1) {}

The third option, using code to set the value of a member variable, should be avoided.