From what I've read, virtual functions are functions in the base class that you can override in its derived classes.
But earlier, when learning about basic inheritance, I was able to override base functions in derived classes without using virtual
.
What am I missing here? I know there is more to virtual functions, and it seems to be important so I want to be clear on what it is exactly.
Best Answer
Here is how I understood not just what
virtual
functions are, but why they're required:Let's say you have these two classes:
In your main function:
So far so good, right? Animals eat generic food, cats eat rats, all without
virtual
.Let's change it a little now so that
eat()
is called via an intermediate function (a trivial function just for this example):Now our main function is:
Uh oh... we passed a Cat into
func()
, but it won't eat rats. Should you overloadfunc()
so it takes aCat*
? If you have to derive more animals from Animal they would all need their ownfunc()
.The solution is to make
eat()
from theAnimal
class a virtual function:Main:
Done.