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

PHOTO EMBED

Wed Apr 14 2021 17:38:00 GMT+0000 (Coordinated Universal Time)

Saved by @wowza12341 #c++

Example:

    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")));
content_copyCOPY

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

https://www.udemy.com/course/learn-advanced-c-programming/learn/lecture/3688272#questions/14612872/