Reputation: 2292
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.
Upvotes: 10
Views: 1321
Reputation: 109119
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.
Upvotes: 9
Reputation: 30489
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
Upvotes: 4