10

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.

Stefan Weiser
  • 2,264
  • 16
  • 25

3 Answers3

9

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.

Community
  • 1
  • 1
Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • FYI, there is a [what changed in C++14](http://stackoverflow.com/a/27511360/1708801) which covers that issue in your first link. – Shafik Yaghmour Jan 14 '15 at 10:23
  • @Shafik I hadn't seen your addition to that answer, it's nice to have all the info in the same place. – Praetorian Jan 14 '15 at 14:30
  • I figured, it is a long scroll down. I only noticed that the addition was needed because R. Martinho Fernandes added a bounty looking for a C++14 answer. – Shafik Yaghmour Jan 14 '15 at 14:40
  • @Praetorian : Similar question, but instead of the non-static member variable, If I create the object for the first struct like this - Foo foo{}, then "int a" would be 0 initialized. why ? – ppadhy Jul 25 '20 at 05:28
  • 1
    @PabitraPadhy Yes, `a` will be 0 because it's value initialized. See https://en.cppreference.com/w/cpp/language/aggregate_initialization – Praetorian Jul 25 '20 at 15:36
4
struct Foo
{
    int a;
}bar;

bar.a is uninitialized if not in global scope or not-static.

struct Foo
{
    int a{};
}bar;

bar.a is initialized to 0

struct Foo
{
    int a{0};
}bar;

bar.a is initialized to 0

So constructs 2 and 3 are same. 1 is different.

For more details, you may want to read Initialization and Class Member Initialization

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • 2 and 3 are not same, even though they do the same thing in *this* case. – Nawaz Jan 14 '15 at 07:09
  • @Nawaz Thanks. I agree with you and do think the same. My point was, in OP's case, empty brace list and a brace list with `0` would exhibit same observable effect. – Mohit Jain Jan 14 '15 at 07:16
1

First one is POD type. Member a is initialized by 0.