Can anyone explain the output of the following code?
#include <iostream>
#include <string>
class Animal
{
public:
Animal(const std::string & name) : _name(name) { }
~Animal() { }
virtual void printMessage() const
{
std::cout << "Hello, I'm " << _name << std::endl;
}
private:
std::string _name;
// other operators and stuff
};
class Cow : public Animal
{
public:
Cow(const std::string & name) : Animal(name) { }
~Cow() { }
virtual void printMessage()
{
Animal::printMessage();
std::cout << "and moo " << std::endl;
}
};
int main() {
Cow cow("bill");
Animal * animal = &cow;
cow.printMessage();
animal->printMessage();
}
The output is
Hello, I’m bill
and moo
Hello, I’m bill
I don’t understand why. The pointer animal points at an object of type Cow. printMessage is a virtual function. Why isn’t the implementation of the Cow class the one that is called?
Cowisn’t overriding the virtual function fromAnimalbecause it has a different signature. What’s actually happening is thatCowis hiding the function inAnimal.The result of this is that calling
printMessageon anAnimalwill just use the version inAnimal, regardless of the one inCow(it isn’t overriding it), but calling it fromCowwill use the one inCow(because it hides the one fromAnimal).To fix this, remove the
constinAnimal, or add theconstinCow.In C++ 2011, you will be able to use the
overridekeyword to avoid subtle traps like this:Notice the added
overrideafterprintMessage(). This will cause the compiler to emit an error ifprintMessagedoesn’t actually override a base class version. In this case, you would get the error.