0

I don't really understand why a class needs to have a default constructor when it is being used as a map value.

If you don't have a default constructor, it will give you an error saying: In template: no matching constructor for initialization

#include <iostream>
#include <map>

class MyClass
{
  public:
     MyClass(int test) {};
     MyClass() {};

};

int main() {
    std::map<int, MyClass> myMap;
    myMap[1] = MyClass(42);
}

This code will give me no error since I have a default constructor. Can someone help me understand why I need a default constructor. Thanks.

  • Because `operator[]` will create an object if it doesn't exist. – ChrisMM Apr 15 '21 at 13:32
  • Replace `myMap[1] = MyClass(42);` with `myMap.emplace(1, 42);`, then you won't need the default constructor in MyClass. – Eljay Apr 15 '21 at 13:43
  • 1
    @Eljay -- those do two different things when there is already an element with a matching key. The first replaces the mapped value and the second leaves the original value in place. – Pete Becker Apr 15 '21 at 14:01
  • @PeteBecker • very true. In the OP's code, there is not already an element with a matching key. For a more general solution, the code would have to check for the key in the map, then either update or emplace accordingly. (In my SQL days, we'd call that an `UPSERT` stored procedure.) – Eljay Apr 15 '21 at 14:04
  • 1
    @Eljay `myMap.insert_or_assign(1, 42);` is the correct equivalent – Caleth Apr 15 '21 at 14:30

0 Answers0