xmllmx
xmllmx

Reputation: 42363

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?

Upvotes: 1

Views: 344

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409176

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
};

Upvotes: 3

kevr
kevr

Reputation: 455

Neither way is better, however, the new uniform initialization has the perk of being similar to other languages and over-all more understandable. Uniform initialization does not only apply to struct members, but also across the board for initializer lists and constructor arguments.

Upvotes: 0

holmicz
holmicz

Reputation: 577

I am not sure, but I think that the first case is possible only with C++ primitive types. In most of the books, especially in book 55 Ways to improve your C++ code by Scott Meyers, it is recommended to go via first way, so I would stick with that. :-)

Don't forget, that order of evaluation and initialization is determined how members in classes are sorted.

I prefer just the second style of initialization.

Upvotes: 2

Related Questions