6

Just an instructive interview question: "What does this C++14 program print?"

#include <iostream>

struct A { int i; };
struct B { 
    A a{1}; 
    operator int() { return a.i; }
};

int main() { 
    B x({});
    B y{{}};
    std::cout << x << y;
}

And it actually prints 10, meaning that the braces in the definition of y change its initial value. But how?

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
  • 2
    The first calls the default constructor which initialises `a` to 1, the second directly initialises `a` to 0 – Alan Birtles Aug 07 '21 at 06:07
  • 4
    The dupe doesn't answer the question. – Evg Aug 07 '21 at 06:18
  • Good question. @AlanBirtles: I know it has to do with aggregate initialization. Could you explain what each brace / parentheses mean? – Bernd Aug 11 '21 at 10:29
  • @Bernd see the duplicate: https://stackoverflow.com/questions/57304873/whats-the-difference-between-parentheses-and-braces-in-c-when-constructing-ob – Alan Birtles Aug 11 '21 at 11:31
  • Does this answer your question? [What's the difference between parentheses and braces in c++ when constructing objects](https://stackoverflow.com/questions/57304873/whats-the-difference-between-parentheses-and-braces-in-c-when-constructing-ob) – cbuchart Jan 27 '23 at 09:33

0 Answers0