Looking at the answer Why do we need virtual functions in C++, they show that virtual functions allow late binding, which results in being able to call subclass functions, when being downcasted.
For completness, I include the code in question.
class Animal
{
public:
virtual void eat() {
std::cout << "I'm eating generic food.";
}
};
class Cat : public Animal
{
public:
void eat() { std::cout << "I'm eating a rat."; }
};
Now consider the following two function
void func(Animal *xyz) { xyz->eat(); }
void func2(Animal xyz) { xyz.eat(); }
We see that calling func results in
Animal *animal = new Animal;
Cat *cat = new Cat;
func(animal); // outputs: "I'm eating generic food."
func(cat); // outputs: "I'm eating a rat."
While calling func2 results in
Animal animal;
Cat cat;
func2(animal); // outputs: "I'm eating generic food."
func2(cat); // outputs: "I'm eating generic food."
My question is:
How can I make it so, that functions receiving arguments, that are not pointers, to instances of subclasses, will use the overriden methods? In other words, how can func2 result in "I'm eating a rat.". Further, I would like to understand why this difference arises. I thank you in advance.