Why do we need default constructors when setting objects as key values


Wed Apr 14 2021 17:38:00 GMT+0000 (UTC)

Saved by @wowza12341 #c++


    people[0] = Person(3, "Bob");
    people[1] = Person(4, "Joe");
    people[2] = Person(5, "Sue");

Example 2:

	people.insert(std::pair <int, Person> (0, Person(3, "Bob")));
	people.insert(std::pair <int, Person> (1, Person(4, "Joe")));
	people.insert(std::pair <int, Person> (2, Person(5, "Sue")));

The above example will give you an error saying: In template: no matching constructor for initialization of 'Person' The map creates an element with key 0/1/2 and an empty Person object for its value, then assigns the value to a temporary Person object. The Person class needs to have a default constructor here, so that an empty Person object can be created. If using .insert the element's value is initialized directly from the temporary Person object, by calling the copy constructor. In this case, the Person class does not need to have a default constructor. This is show in the second example