I have the following class and some constructors:
default constructor assigns empty string and 0
copy constructor copies reference's field to the instance's filed
explicit constructor takes in one string and one integer and assigns them to the field
- Without the lines between the "//////", the output is like
explicit constructor
default constructor
My understanding is: the right hand side is evaluated first. That is using an explicit constructor. It then creates one entry with default constructor and assigns the fields from the instance constructed with explicit constructor to the instance constructed by the default constructor.
ppl[0] = Person("Mike", 20);
- With the lines bwtween "////", the output looks like
explicit constructor
default constructor
explicit constructor
copy constructor
copy constructor
The first two are just like above. How about explcit + copy + copy? I think the explicit is for Person("jo", 10). How to explain the two copy constructor?
class Person{
private:
string name;
int age;
public:
Person(){
cout<<"default constructor"<<endl;
name="";
age = 0;
}
Person(const Person &other){
cout<<"copy constructor"<<endl;
name = other.name;
age = other.age;
}
Person(string name, int age){
cout<<"explicit constructor"<<endl;
this->name = name;
this->age = age;
}
};
int main(){
map<int, Person> ppl;
ppl[0] = Person("Mike", 20);
////////////////////////////////////////////
ppl.insert(make_pair(1, Person("jo", 10)));
////////////////////////////////////////////
return 0;
}