Iterate over a list of objects

I have declared a list like this:
list<Animal*> animals;

I have then filled the list with some animals (classes that are derived from Animal, like Dog, Cat etc, like:
1
2
Dog *dog = new Dog("Fido");
animals.push_back(dog);


Now I would like to iterate over all elements in the list and call the getName() method that is declared in Animal.

1
2
3
4
5
list<Animal*>::iterator it;
for(it=animals.begin(); it!=animals.end(); it++)
{
     cout << *it->getName() << endl; // compile error
}

How do I call the getName() function?
Try
 
(*it)->getName()
Ah, thanks!
I also would like to get the Dogs out of the list with animals.

I have tried to cast to Dog like this:
1
2
3
4
5
6
list<Animal*>::iterator it;
for(it=animals.begin(); it!=animals.end(); it++)
{
     Dog *dog = dynamic_cast<Dog*>(*it); // compile error
     cout << *dog->feedDog() << endl; 
}


How do I cast to a derived class in C++?
The cast is correct (as long as Animal is a polymorphic class). What is the compile error you're getting?
It's more likely that it's the next line that's causing it, it should be
if (dog)cout << dog->feedDog() << endl;
(unless feedDog() returns some type of pointer).
"source is not polymorphic" is the compiler error I get.

I made the ~Animal() destructor virtual, because I read that at least one function has to be virtual to make the base class polymorphic.

Is the making of the base class' destructor virtual a good practice?
Yes, if your class is polymorphic, the destructor should always be virtual.
Base class destructors should always be either public and virtual or protected and non-virtual.

Anyway, the "is not polymorphic" error is probably saying that one of your object's types does not inherit from Animal. Just post the code rather than a few lines and it's easier/faster for us to identify the problem(s).
Sorry, forgot to mention in my previous post that I solved it by declaring ~Animal() destructor virtual.

Thanks for your answers!
Topic archived. No new replies allowed.