I've just started using maps in C++, I implemented this piece of code where I've used custom datatype for map values. But I haven't understood the copy constructor part. It's being called multiple times only when I use
person.insert(make_pair(55,Person("Bob",23)));
person.insert(make_pair(35,Person("Bill",25)));
Can someone kindly explain me the working of the copy constructor in this code ??
#include<iostream>
#include<map>
using namespace std;
class Person{
private:
string name;
int age;
public:
Person(const Person &other){
cout<<"Copy Constructor Running !!"<<endl;
name=other.name;
age=other.age;
}
Person():name(""),age(0){
}
Person(string name,int age):name(name), age(age){
}
void print(){
cout<<name<<" : "<<age<<endl;
}
};
int main(){
map<int,Person> person;
person[50]=Person("Mike",19);
person[20]=Person("Julia",20);
person[30]=Person("Raj",29);
person[10]=Person("Kendra",20);
person[70]=Person("Rahul",18);
person.insert(make_pair(55,Person("Bob",23)));
person.insert(make_pair(35,Person("Bill",25)));
for(auto it=person.begin();it!=person.end();it++){
cout<<it->first<<" : ";
it->second.print();
}
return 0;
}
OUTPUT:
Copy Constructor Running !!
Copy Constructor Running !!
Copy Constructor Running !!
Copy Constructor Running !!
10 : Kendra : 20
20 : Julia : 20
30 : Raj : 29
35 : Bill : 25
50 : Mike : 19
55 : Bob : 23
70 : Rahul : 18
Aucun commentaire:
Enregistrer un commentaire