c++c++11initializer-list

error: too many initializers for a struct


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?


Solution

  • 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