Why the virtual makeNoise method of the base class is called instead of the method of the inherited class when I iterate through the list of Animal objects in following code. If I call directly the makeNoise method from the inherited objects then the right out put is printed out.
#include <iostream>
#include <list>
class Animal {
public:
Animal() {
}
virtual ~Animal() {
}
virtual void makeNoise() {
std::cout << "This animal makes no sound." << std::endl;
}
};
class Dog: public Animal {
public:
virtual void makeNoise() {
std::cout << "Wuf!" << std::endl;
}
};
class Cat: public Animal {
public:
virtual void makeNoise() {
std::cout << "Maouw!" << std::endl;
}
};
int main() {
std::list<Animal> listOfAnimals;
Animal * cat = new Cat();
Animal * dog = new Dog();
listOfAnimals.push_back(*cat);
listOfAnimals.push_back(*dog);
for (std::list<Animal>::iterator it = listOfAnimals.begin();
it != listOfAnimals.end(); ++it) {
it->makeNoise();
}
cat->makeNoise();
dog->makeNoise();
return 0;
}
The output looks like:
This animal makes no sound.
This animal makes no sound.
Maouw!
Wuf!
I would expect the noises of Cat and Dog to be printed out also while iterating. That is the functionality of virtual method as I would understand it. Does the type definition of the list affect it somehow?