Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-static data member initialization

Tags:

c++

c++11

Are there any differences between the following three structure definitions according to the C++ standard?

struct Foo
{
    int a;
};

struct Foo
{
    int a{};
};

struct Foo
{
    int a{0};
};

The last two are C++11.

like image 409
Stefan Weiser Avatar asked Jan 14 '15 06:01

Stefan Weiser


1 Answers

Given the first definition, if you create an instance of Foo with automatic storage duration, a will be uninitialized. You can perform aggregate initialization to initialize it.

Foo f{0};  // a is initialized to 0

The second and third definitions of Foo will both initialize the data member a to 0.

In C++11, neither 2 nor 3 are aggregates, but C++14 changes that rule so that they both remain aggregates despite adding the brace-or-equal-initializer.

like image 135
Praetorian Avatar answered Oct 17 '22 12:10

Praetorian