1

I have a Mammal parent class. Dog, Cat, Lion are the sub-classes.

I am using vectors to hold all the sub-classes as Mammal object as such

vector<Mammal> v;

And using this line to append new objects to the vector.

v.push_back(new Dog(Name, Blue, Owner));

Apparently it doesn't work. Error no instance of overload function is thrown to me during compile. I am new to C++ so I am not sure what is the correct way to dynamically create an array of parent class to hold all the child object

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Gavin
  • 2,784
  • 6
  • 41
  • 78
  • First of all you should read about [*object slicing*](https://en.wikipedia.org/wiki/Object_slicing). Second of all, using `new` results in a *pointer*, and you have a vector of object and not a vector of pointers. Thirdly, when posting questions about build errors, please include the complete and unedited error output in the question. – Some programmer dude Nov 06 '15 at 07:12
  • Same as in your previous question: polymorphism **only** with pointers or references. – Daniel Jour Nov 06 '15 at 07:19

2 Answers2

6

buchipper already gave you good advice. When you want to manage the lifetime of your pets correctly, consider to use std::unique_ptr<> or std::shared_ptr<> instead of raw pointers:

// the vector owns the pets and kills them, when they are removed
// from the vector
vector<std::unique_ptr<Mamal> > v1

// the vector has shared ownership of the pets. It only kills them,
// when noone else needs them any more
vector<std::shared_ptr<Mamal> > v2

// the vector has no ownership of the pets. It never kills them.
vector<Mamal*> v3

In the last case, someone else has to take care of the pets death, or they'l hang around in your memory as zombies. You don't want to to that to your pets, do you?

Update Oh, i forgot to mention, that you should prefer make_shared() and make_unique() over new, or use emplace_back() instead of push_back()

v1.emplace_back(new Dog{Name, Blue, Owner});
v1.push_back(make_unique<Dog>(Name, Blue, Owner))

v2.emplace_back(new Dog{Name, Blue, Owner});
v2.push_back(make_shared<Dog>(Name, Blue, Owner))
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
cdonat
  • 2,748
  • 16
  • 24
1

As already mentioned in the comments, you have a vector of Mammal objects and not pointers or references.

Try -

vector <Mammal *> v;
v.push_back(new Dog(Name, Blue, Owner));
buchipper
  • 606
  • 4
  • 16