dani
dani

Reputation: 3887

Static, private member of a class internal type

I've a class myClass that has a type defined in it, myType, and a static const std::map that uses this type. How must I initialise the member?

The situation is like this. The compiler tells me: multiple definition of MyClass::myMap. But there is really only one definition. Is this initialisation (schematically) correct?

class myClass
{
  struct myType
  {
    // ...
  };
  static const std::map<int, myType> myMap;
};

const std::map<int, myType> myClass::myMap = {
  {1, {"hello myType", 99, "woops"}},
  {2, {"hello again", 66, "holla"}},
  {3, {"and bye", 33, "adios"}}
};

It's not a duplicate because the const members in the proposed question are not static.

Also this question: Initializing private static members does not answer the question since the static const members are int's.

Upvotes: 0

Views: 128

Answers (1)

Kevin Grant
Kevin Grant

Reputation: 5431

As written, both the declaration and definition are in the same file. If you do this, and you "#include" the file in more than one place, there will be multiple definitions created.

The static value is typically initialized separately, in a C++ source file and not in the header file with the class.

Upvotes: 2

Related Questions