I found some excellent threads on this site for the subject, and the topic of polymorphism is cleared up for me, but I'm just confused how exactly a virtual function works versus a normal function.
(an example given in this thread Why do we need virtual functions in C++?):
class Animal
{
public:
void eat() { std::cout << "I'm eating generic food."<<endl; }
};
class Cat : public Animal
{
public:
void eat() { std::cout << "I'm eating a rat."<<endl; }
};
void func(Animal *xyz) { xyz->eat(); }
So We have a function and a derived function that was redefined.
Cat *cat = new Cat;
Animal *animal = new Animal;
animal->eat(); // Outputs: "I'm eating generic food."
cat->eat(); // Outputs: "I'm eating a rat."
func(animal); // Outputs: "I'm eating generic food."
func(cat); // Outputs: "I'm eating generic food."
So we can't access the function we want without it being a virtual function. But why, exactly?
If the following works:
Cat cat;
Animal animal;
animal.eat(); // Outputs: "I'm eating generic food."
cat.eat(); // Outputs: "I'm eating a rat."
Then presumably there are two different eat functions in memory already without needing a vtable.
So when we make eat a virtual function, each class now gets its own vTable with its own functions. So...We are just storing the functions in another place in memory. So what happens to a pointer between when it calls a regular function through an object and when it calls a virtual function through an object?
As in what's the difference between: Animal->eat(); //Calling a virtual function and Animal->eat(); //Calling a regular function
When we declare virtual function, TutorialsPoint says
This time, the compiler looks at the contents of the pointer instead of it's type
Yes, but how? Why couldn't it do that before? It's presumably just stored in memory the same as a regular function. Does it have something to do with the Vtable pointer at the beginning of an object?
I'm just looking for specifics to understand why. I don't mean to sound like I'm getting bogged down in something ultimately pointless. Just wondering for academic reasons.