I have the following class hierarchy: Crocodile Class extends from Oviparous which extends from Animal
I need to store objects of type Crocodile, Goose, Pelican, Bat, Whale and SeaLion inside a vector, so:
1- I create the global vector:
vector<Animal*> animals;
2- I add objects (Crocodile, Goose, Pelican, Bat, Whale, SeaLion) to the vector:
animals.push_back(new Crocodile(name, code, numberofEggs));
3- I loop through the vector to print each object on a table
for (size_t i = 0; i < animals.size(); ++i){
/* now the problem is here, each animal[i] is of type = "Animal", not Crocodile, or Goose, etc..
/* so when I try to do something like the line below it doesn't work because it can't find the method because that method is not on the Animal Class of course */
cout << animals[i]->GetName(); // THIS WORK
cout << animals[i]->GetNumberofEggs(); //THIS DOESN'T WORK
/* when I debug using the line below, every object on the vector is returning "P6Animal" */
cout << typeid(animals[i]).name(); // P6Animal instead of Crocodile
}
I think it is related with this post std::vector for parent and child class and I think the problem is object slicing, so I tried creating the vector like this:
vector<unique_ptr<Animal>> animals;
//and adding the objects like this
animals.push_back(unique_ptr<Animal>(new Crocodile(name, code, numberofEggs)));
But nothing
Any help would be great! Thank you!