xmllmx xmllmx - 10 days ago 6
C++ Question

How to properly initialize the data members in C++11?

In C++11, we have two ways to initialize the data members of a class/struct as illustrated in the following examples:

struct A
{
int n = 7;
};

struct B
{
int n;

B() : n(7) {}
};


Question 1:

Which way is better?

Question 2:

Is the traditional way (the latter) not encouraged from the view of a modern-C++-style checker?

Answer

You can actually mix both styles. This is useful if you have multiple constructors, but the variables is only specifically initialized by one or a few of the constructors.

Example

struct A
{
    int n = 7;

    A() {}  // n will be initialized to 7
    A(int n_) n{n_} {}  // Initialize n to something else
};
Comments