Vector of class type.

Hi I am making an address book and it is going smoothly, however I have come across an issue that has been solved but I do not why it is fixed. If that makes sense? Well anyway I will show my class, the initial problem and the solution to that problem that I stumbled upon.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Person
{
private:
	int age;
	string number;
	string fname, lname;
public:
	void setName();
	void setAge();
	void setNumber();
	void display();
	Person();
	~Person();
};


I initially made a Person vector like so:

 
vector<Person> List;


However whenever I tried to use pushback() it would never work and the errors I got had * and & in them so I thought it was to do with pointers. So I corrected the above to so:

vector<Person*> List;

This seemed to fix the problem. However I do not know why. Here is the context that I am using it in:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void addPerson()
{
	cout<< "Please enter the number of contacts you wish to add:";
	int n = 0;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		List.push_back(new Person);
	}

	for (int i = 0; i<List.size(); i++)
	{
		List.at(i)->display();
	}

}


Finally one quick question. I have made a destructor like so:

1
2
3
4
5
6
7
8
Person::~Person()
{
	delete &age;
	delete &number;
	delete &fname;
	delete &lname;

}


Is this the correct way?

Thanks for your time.
new finds a free block of memory, constructs a Person in it and then returns a pointer to that block. new is not necessary here. You could work with
1
2
3
vector<Person> List;
List.push_back(Person());
List.at(i).display();


The destructor is bad. There has to be one delete for every new. These members were never created with new, so there can't be delete either. Most classes you'll work with don't need a destructor. In your code using a vector<Peron*> you should (at the end of the program) iterate over the vector, deleting every element. Although it is simpler not to use pointers here.
Last edited on
Thanks I understand it now.
Topic archived. No new replies allowed.