I have the following simple inheritance example in C++.
#include<bits/stdc++.h>
using namespace std;
class Animal{
public:
string mName;
Animal(string pName){
mName=pName;
}
virtual void printAnimal(){
cout<<"Animal "<<this->mName<<endl;
}
};
class Dog: public Animal{
public:
Dog(string pName): Animal(pName){}
void printAnimal(){
cout<<"Dog "<<this->mName<<endl;
}
};
class Cat: public Animal{
public:
Cat(string pName): Animal(pName){}
void printAnimal(){
cout<<"Cat "<<this->mName<<endl;
}
};
Animal getCat(){
return Cat("Tom");
}
Animal getDog(){
return Dog("Scooby");
}
int main(){
getCat().printAnimal();
getDog().printAnimal();
}
To my understanding, if we override a virtual function given in the base class, then no matter whether the reference is to the base class or the derived class, when the overridden function is called, it should call the function defined in the derived class and not the base class.
So one would expect the output of the above program to be,
Cat Tom
Dog Scooby
But I get,
Animal Tom
Animal Scooby
Why is this happening? What is the correct way to do this?