1

Someone gave me (part of) the following code:

struct MyStruct
{
    int x = {};
    int y = {};

};

I never saw this syntax before, what does initialization with {} mean?

Benny K
  • 1,957
  • 18
  • 33
  • See this answer: https://stackoverflow.com/questions/18222926/why-is-list-initialization-using-curly-braces-better-than-the-alternatives – Istvan May 12 '20 at 06:00
  • 1
    It's inline [*value initialization*](https://en.cppreference.com/w/cpp/language/value_initialization) of the members. In short, `int x = {};` is the same as `int x = 0;`. – Some programmer dude May 12 '20 at 06:01
  • @Someprogrammerdude but I can't just replace it with `int x = 0` unless it is `const`? – Benny K May 12 '20 at 07:11
  • 1
    @BennyK `int x = 0;` should be fine. https://wandbox.org/permlink/NEGqlNIcI8nieHe5 – songyuanyao May 12 '20 at 07:20
  • Does this answer your question? [Why is list initialization (using curly braces) better than the alternatives?](https://stackoverflow.com/questions/18222926/why-is-list-initialization-using-curly-braces-better-than-the-alternatives) – ChrisMM May 12 '20 at 14:49

2 Answers2

3

This is default member initializer (since C++11),

Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

The initialization itself is copy-list-initialization (since C++11), as the effect, the data member x and y would be value-initialized (and zero-initialized as built-in type) to 0.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • It's default member initializer, not default initializer list. – super May 12 '20 at 06:14
  • @songyuanyao The data member would be initialized to its default value. In the case of `int` it is `0`. But for classes it will mean constructing with the default constructor. – Enosh Cohen May 12 '20 at 06:23
  • @EnoshCohen There's no "default value" for int in this context. – juanchopanza May 12 '20 at 06:30
  • There is an "initial value" for scalar types, maybe the term is not accurate: https://en.cppreference.com/w/cpp/language/zero_initialization – Enosh Cohen May 12 '20 at 06:40
1

Since the C++11 standard there are two ways to initialize member variables:

  1. Using the constructor initialization list as "usual":

    struct Foo
    {
        int x;
    
        Foo()
            : x(0)
        {
        }
    };
    
  2. Use the new inline initialization where members are getting their "default" values using normal initialization syntax:

    struct Foo
    {
        int x = 0;
    };
    

Both these ways are for many values and types equivalent.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621