Kasair
Kasair

Reputation: 11

Adding multiple pointers of the same type to vector

I have an vector of pointers in which i want to store pointers to objects of same type

Parent * tempParent=new Parent();

vector<Parent *> parents;
for(int i=0;i<9;i++){
  tempParent.setAge(i);
  parents.push_back(tempParent);
}

What this does it sets all parents age to 8. Any ideas how could I make them point to a different objects so that they all have different age? Thanks

Upvotes: 1

Views: 178

Answers (2)

0x6773
0x6773

Reputation: 1116

You need to create 9 different objects of Parent so they will point to 9 different object.I think this code will help you :

vector<Parent *> parents;
for(int i=0;i<9;i++)
{
    Parent * tempParent=new Parent();
    tempParent->setAge(i);
    parents.push_back(tempParent);
}

Upvotes: 0

Jack
Jack

Reputation: 133577

If you want to store 9 Parent objects in a std::vector then you need to create 9 of them.

You have multiple solution to the problem, you can just store plain objects (and not pointers, since you don't have to store pointers if you don't need them), eg:

std::vector<Parent> parents;
for (int i = 0; i < 9; ++i) {
  parents.push_back(Parent(i)); // assuming a Parent::Parent(int age) constructor
}

If you really want pointers you need to call new 9 times by sure:

std::vector<Parent*> parents;
for (int i = 0; i < 9; ++i) {
  Parent* parent = new Parent(i);
  parents.push_back(parent);
}

Mind that if you really need pointers wrapping them inside an unique_ptr is a good idea if the vector has ownership on them:

std::vector<std::unique_ptr<Parent>> parents;
parents.push_back(std::unique_ptr<Parent>(new Parent(age));

Upvotes: 4

Related Questions