I have several classes that inherit from one main class. For the sake of simplicity, I have over-simplified the class definitions to make it short and direct to the point.
animal.h
main class which all other classes inherit from:
class Animal {
protected:
string name;
public:
Animal(string name);
virtual string toString() { return "I am an animal"; }
};
bird.h
class Bird: public Animal {
private:
bool canFly;
public:
Bird(string name, bool canFly = true)
: Animal(name) // call the super class constructor with its parameter
{
this->canFly = canFly;
}
string toString() { return "I am a bird"; }
};
indect.h
class Insect: public Animal {
private:
int numberOfLegs;
public:
Insect(string name, int numberOfLegs) : Animal(name) {
this->numberOfLegs = numberOfLegs;
}
string toString() { return "I am an insect."; }
};
Now, I need to declare a vector<Animal>
that will hold several instances of each inherited class.
main.cpp
#include <iostream>
#include "animal.h"
#include "bird.h"
#include "insect.h"
// assume that I handled the issue of preventing including a file more than once
// using #ifndef #define and #endif in each header file.
int main() {
vector<Animal> creatures;
creatures.push_back(Bird("duck", true));
creatures.push_back(Bird("penguin", false));
creatures.push_back(Insect("spider", 8));
creatures.push_back(Insect("centipede",44));
// now iterate through the creatures and call their toString()
for(int i=0; i<creatures.size(); i++) {
cout << creatures[i].toString() << endl;
}
}
I expected the following output:
I am a bird
I am a bird
I am an insect
I am an insect
but I got:
I am an animal
I am an animal
I am an animal
I am an animal
I know this has to do with the line 'vector creatures;. It is calling the constructor for
Animal. But my intention is to tell the compiler, that this
creaturespoints to an array of
Animalinherited classes, might be
Birdmight be
insect, the point is: they all implement their own unique respective version of
toString()`.
What can I do to declare a polymorphic array of objects that are inherited from the same ancestor?