Search code examples
c++c++11structureinitializer-list

Structure initialization error: could not convert from ‘<brace-enclosed initializer list>’ to structure


I have the following code:

struct Vec { double x=0, y=0, z=0; };

Vec orig = {1,2,3};

GCC 4.8.4 shows the following error:

error: could not convert ‘{1, 2, 3}’ from ‘<brace-enclosed initializer list>’ to ‘Vec’
 Vec orig = {1,2,3};
                  ^

When I change take away the equals sign

Vec orig {1,2,3};

there comes another error:

error: no matching function for call to ‘Vec::Vec(<brace-enclosed initializer list>)’
 Vec orig {1,2,3};
                ^

How can I initialize the structure properly without creating a constructor?


Solution

  • Looks like you are using c++11, but not yet c++14.

    Once you provide default member initializers, the class is no longer an aggregate, and you cannot use aggregate initialization.

    https://en.cppreference.com/w/cpp/language/aggregate_initialization

    An aggregate is one of the following types:

    ...

    • class type (typically, struct or union), that has

      ...

      • no default member initializers (until c++14)