0

I'm trying some code with c++11,

  struct Data {};

  struct B {
    B(Data data) : m_data{data} {}
    Data m_data{};
  };

it complains error: too many initializers for 'Data'

what is wrong?

[UPDATE] thanks guys, there is something wrong with my toolchain configuration.

pepero
  • 7,095
  • 7
  • 41
  • 72

2 Answers2

3

You get that error string when you do not enable c++11 mode or later in older GCC compilers (that defaults to c++03).

main.cpp:4:31: error: too many initializers for 'Data'
B(Data data) : m_data{data} {}

See it here. Although newer versions of GCC will give you more helpful diagnostics to enable c++11 mode.

So, just add to your compiler invocation:

-std=c++11
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
0

That's correct c++11, but maybe you are not compiling in C++11 mode.

Many compiler still defaults to C++98, and you typically need to activate a command line switch (or an option in your IDE) to enable C++11 syntax.

I've added to your code a small main:

int main()
{
    Data d;
    B b(d);
}

... and it compiles clean both with gcc 5.x and clang 802 (xcode 8 version), provided I add on the command line:

-std=c++11

gabry
  • 1,370
  • 11
  • 26