I was trying to understand virtual functions.
Consider the following code,
#include <iostream>
#include <memory>
#include <vector>
class Animal
{
public:
virtual void eat()
{
std::cout << "I eat like a generic animal.\n";
}
};
class Wolf : public Animal
{
public:
void eat()
{
std::cout << "I eat like a wolf!\n";
}
};
int main()
{
Animal a;
Wolf w;
a.eat();
w.eat();
}
With the virtual keyword I get the output
I eat like a generic animal.
I eat like a wolf!
as it should.
But If I remove the virtual keyword I still get the same output! From my
elementary understanding of virtual functions, without the virtual I should have got the output
I eat like a generic animal.
I eat like a generic animal.
Is there anything elementary here I am missing ?
I am using the g++ compiler on Linux
Polymorphism works by identifying the type of object that an instance actually refers to.
In your case, your actual animals are as follows:
So, you’re not using polymorphism at all.
What you need to do is more like this:
Note that you can use pointers or references to achieve this use of polymorphism.
That is why you should usually pass objects by const-reference when working with class types.
Note that slicing means it will turn a more derived class (wolf) into a less derived copy of that class (animal) indiscriminately which can be very misleading and unexpected.