What is a virtual function?
This makes sense, right? class Animal { public: void eat() { cout << "I'm eating generic food."; } } class Cat : public Animal void eat() { cout << "I'm eating a rat."; } Animal *animal = new Animal; Cat *cat = new Cat; animal->eat(); // outputs: "I'm eating generic food." cat->eat(); // outputs: "I'm eating a rat."
Whoa, what happened? void dinner(Animal *xyz) { xyz->eat(); } Animal *animal = new Animal; Cat *cat = new Cat; dinner(animal); // outputs: "I'm eating generic food." dinner(cat); // outputs: "I'm eating generic food."
The compiler made a compile time decision. At compile time, dinner didn’t know what was being passed. It did the only thing it could. We want to ask for a RUN TIME decision. We want to say, if dinner got an animal, call animal eat. BUT if dinner got a cat, call cat’s eat. This is why we need virtual.
Now a run time decision is made. class Animal { public: virtual void eat() { cout << "I'm eating generic food."; } } dinner(animal); // outputs: "I'm eating generic food." dinner(cat); // outputs: "I'm eating a rat."