I am iterating through a list of Animal
objects (which contains 3 or 4 different types of objects all subclassing from Animal
):
foreach (Animal entry, animalList)
{
switch(entry.animalType)
{
case Animal::tiger:
qDebug() << static_cast<Tiger>(entry).tigerString;
break;
}
}
This gives me the following error:
no matching function for call to 'Tiger::Tiger(Animal&)'
So I tried:
static_cast<Tiger*>(entry).tigerString;
Which gives me the following error:
invalid static_cast from type 'Animal' to type 'Tiger*'
So finally I decided to change entry
to a pointer type like so:
foreach (Animal* entry, animalList)
etc....
And I get the following error:
cannot convert 'const value_type {aka const Animal}' to 'Animal*' in initialization
Am I missing something here? I absolutely need to get tigerString
which is a string specific to the subclass Tiger
.
What should I be doing?
UPDATE Please see the following (the code has been stripped for cleanliness):
std::list<Animal*> animalList;
Tiger *myTiger = new Tiger();
myTiger->animalType= Animal::tiger;
myTiger->tigerString= "I am a tiger";
animalList.push_back(myTiger, animalList);
foreach (Animal* entry, animalList)
{
Tiger* tiger = dynamic_cast <Tiger*> (entry);
if (tiger)
{
// It is a tiger
}
else
{
// it is NOT a tiger
}
}
I get the following error at the first line in the foreach loop
:
cannot dynamic_cast 'animal' (of type 'class Animal*') to type 'class Tiger*' (source type is not polymorphic)