8

I'm debugging some code that essentially is identical to this:

struct Foo { int a; int b; };
struct Bar { Bar() {} Foo foo{0}; };

When I make an instance of Bar, it seems like both a and b are initialized to zero. Is this guaranteed? Where can I find that in the spec?

Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
XPlatformer
  • 1,148
  • 8
  • 18
  • 1
    try: `struct Foo { int a{}; int b{}; };` mind the extra braces after the variable names. then you will always get initialized values. if you need to init with other values, with defined behavior, you need to write a ctor like for a every other class – skratchi.at Oct 28 '19 at 12:12
  • @skratchi.at Those are not parentheses (using parentheses would mean something else) – Lightness Races in Orbit Oct 28 '19 at 12:13
  • 2
    Such a simple question on the surface, but C++ init is so complicated that I understand why you're asking it. I could hazard a guess that you're getting proper aggregate init here _but_ without delving into the standard I am not sure what the answer is. How sad is that? – Lightness Races in Orbit Oct 28 '19 at 12:14
  • This is for arrays, but... https://stackoverflow.com/questions/1065774/initialization-of-a-normal-array-with-one-default-value – YSC Oct 28 '19 at 12:44
  • Another similar question: https://stackoverflow.com/questions/1069621/are-members-of-a-c-struct-initialized-to-0-by-default – Frodyne Oct 28 '19 at 12:46
  • @YSC The question leaves C/C++ open as well... But the accepted answer would definitely apply to this question, so ¯\\_(ツ)_/¯ – eike Oct 28 '19 at 12:54
  • @eike That's true. And this is what matters. The help text of a question closed as duplicate is something in the line of "this question have already been answered here". It doesn't matter if the question is not exactly the same; what matters is that OP can find an answer to their question by following the link. – YSC Oct 28 '19 at 12:58
  • @YSC In that case, this should probably be closed as duplicate – eike Oct 28 '19 at 13:00

1 Answers1

5

According to cppreference.com

If the number of initializer clauses is less than the number of members [and bases (since C++17)] or initializer list is completely empty, the remaining members [and bases (since C++17)] are initialized [by their default member initializers, if provided in the class definition, and otherwise (since C++14)] by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). If a member of a reference type is one of these remaining members, the program is ill-formed.

Foo has no default member initializers (int b{0};), so b will be initialized by list-initialization with an empty list, which means value-initialization for non-class types: b = int() // = 0.

eike
  • 1,314
  • 7
  • 18