Search code examples
c++initialization

Initializing class members with {}


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?


Solution

  • 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.