Copy constructors with maps

Hi guys,sorry for asking so many questions,this thing is really confusing me


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  class Person {

public:

	string name;
	int age;

	Person() :
			name(" "), age(0) {
		cout << "normal constructor called" << endl;
	}
	Person(string n, int a) {

		name = n;
		age = a;
		cout << "two param constuctor called" << endl;
	}
	Person(const Person& other) {

		name = other.name;
		age = other.age;

		cout << "copy constructor called" << endl;
	}
};

int main() {

	map<int,Person> people;

	 people[0] = Person("Mike",20);
	 people[1] = Person("Bill",30);
	 people[2] = Person("Mike",40);
}



this is the output

two param constuctor called
normal constructor called
two param constuctor called
normal constructor called
two param constuctor called
normal constructor called

how come both two param and normal constructor are called,

also how come the copy constructor isn't called how does people[0] get "copied" or the information from the person for example

people[0] = Person("Mike",40);

I thought this would use the copy constructor because we are using =?



also last but not least,how come

people.insert(make_pair(55,Person("Bob",45)));

will call the copy constructor? why isn't the constructors called like in the other example

thanks
people[0] causes a Person object to be created using the default constructor

I thought this would use the copy constructor because we are using =?
= is the assignment operator. It will cause Person& operator=(Person other) to be called.




Last edited on
Topic archived. No new replies allowed.