Take the following C++ for example.
vector listAnimal;
class Fish : Animal ...
class Mammal : Animal ...
class Bird : Animal ...
A container only stores elements of a fixed type, you want a pointer to an object.
#include
#include
std::vector> animal_list;
animal_list.emplace_back(new Fish);
animal_list.emplace_back(new Mammal);
animal_list.emplace_back(new Bird );
Store Animal
type in vector will cause object slice
when push derived types into listAnimal.
vector listAnimal;
listAnimal.push_back(Fish); // Fish is sliced to Animal, no fish for you.
Edit:
To know what type a derived animal is, you could store it in a member
Enum AnimalType
{
FISH,
MAMAL,
BIRD
};
class Animal
{
public:
Animal(AnimalType animal_type) : type(animal_type) {}
AnimalType GetType() const { return type; }
private:
AnimalType type;
};