1

I have a map with a string key and a struct value, I don't know why I cannot instantiate an object using a list of initializers:

#include <string>
#include <map>    
using namespace std;

struct CodeInfo
{
    int _level = 0;
    bool _reactive;
};
typedef map<string, CodeInfo> CodeInfos; // Key is code name

int main()
{
    CodeInfos codes = { {"BARECODE", { 0, true }}, {"BARECODE2", { 0, false }} };

    return 0;
}

It seems to be straight forward but I can't understand why I get the following error:

In function 'int main()':    
24:80: error: could not convert '{{"BARECODE", {0, true}}, {"BARECODE2", {0, false}}}' from '<brace-enclosed initializer list>' to 'CodeInfos {aka std::map<std::basic_string<char>, CodeInfo>}'

I have using compiler g++ (GCC) 4.9.1 20140922 (Red Hat 4.9.1-10) with C++11.

JeJo
  • 30,635
  • 6
  • 49
  • 88
RedPaladin
  • 784
  • 2
  • 9
  • 18

1 Answers1

3

The reason is CodeInfo is not aggregate, because you are initializing one of the data members(_level = 0) directly in the definition of the class.

Removing the default initialization of that member will work with C++11. See here

Read this post for more information about aggregates: What are Aggregates and PODs and how/why are they special?

JeJo
  • 30,635
  • 6
  • 49
  • 88
  • "This is equivalent to providing default constructor to the class and hence will not work with list-initialization." No, not really. – cpplearner Dec 10 '18 at 11:08
  • And we don't usually call `int _level = 0;` "direct initialization". The standard uses the term "default member initializer". – cpplearner Dec 10 '18 at 11:09
  • @cpplearner Thanks for pointing out the right word. And regarding the *default constructor* , that I have found in the other answer. Could you point out me, what exactly is the difference.? – JeJo Dec 10 '18 at 11:16