Problem with vector and copy constructor

I tried to make a list of Person objects using vector and got some weird error. If I remove the copy constructor it works. Is there a way to make a vector while keeping the constructor?

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
#include <iostream>
#include <vector>
using namespace std;

class Person{
        string name; int age;
public:

Person(Person &P){
        name = P.name; age = P.age;
}

void input(){
	cout << "Name: ";
	getline(cin, name);
	cout << "Age: ";
	cin >> age;
	cin.ignore();
}
};

int main(){
	vector<Person> list;
	
	Person A;
	for(int i = 0; i < 3; i++){
		cout << "\nPerson " << i + 1 << endl;
		A.input();
		list.push_back(A);
	}
}
Now you have defined a constructor (in this case your copy constructor) the default constructors become unavailable. But your program requires a constructor that takes no arguments - so define one. It doesn't actually have to do anything.

You could also do with a const before the argument of your copy constructor.
Last edited on
You need a default constructor. Once you define a constructor, you no longer get the default ones! In this case you don't actually need the copy constructor. The default one is fine. so L11 L12 can be removed below.

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
35
36
37
38
39
40
41
#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Person {
	string name;
	int age{};

public:
	Person() {}
	Person(const Person& P) : name(P.name), age(P.age) {}

	void input() {
		cout << "Name: ";
		getline(cin, name);

		cout << "Age: ";
		cin >> age;
		cin.ignore();
	}

	void display() const {
		cout << name << "  " << age << '\n';
	}
};

int main() {
	vector<Person> list;
	Person A;

	for (size_t i = 0; i < 3; ++i) {
		cout << "\nPerson " << i + 1 << '\n';
		A.input();
		list.push_back(A);
	}

	cout << '\n';
	for (const auto& p : list)
		p.display();
}

Last edited on
Topic archived. No new replies allowed.