C++ std::maps and class values with constructors

3455 views c++

It's been a long time since I've seen C++ -- 30 years of more, and obviously, things have changed a lot. I'm also spoiled with Scala, Julia etc, which take care of this magic under the covers, but... no more.... I'm tryihng to figure out why this doesn't work:

class Foo {
   uint_fast8_t val1;
   std::string name;
   uint_fast16_t val2;

std::map<std::string, Foo> myMap;

myMap["Test"] = { 1, "Test2", 2 };

This fails to compile because several operators need to be overloaded for map to work. Note, this happens evne with a constructor defined such as

Foo(uint_fast8_t v1, std::string s, uint_Fast16_t v2) { }; 

If I just do a

myMap["Test"] = Foo()

This works because the constructor has the expected number of arguments (0) as opposed to 3. It's probably basic, and I'm sure I'm showing how long it's been, but what did I miss?

answered question

This pretty much has nothing to do with map. Classes are not structs, members are private, therefore no default value initialization via list initializer. Checkout list initialization.

1 Answer


You have a class with default constructor,which takes zero arguments. And you are trying to create he inline object with passing the three arguments. I will suggest to add the parameterized constructor.

class Point { 
    int x, y; 

    // Parameterized Constructor 
    Point(int x1, int y1) 
        x = x1; 
        y = y1; 


// Constructor called 
Point p1(10, 15);

Basic C++ constructor types can be checked at link

posted this

Have an answer?


Please login first before posting an answer.