eat(); // outputs: "I'm eating generic food." cat->eat(); // outputs: "I'm eating a rat.""> eat(); // outputs: "I'm eating generic food." cat->eat(); // outputs: "I'm eating a rat."">
Download presentation
Presentation is loading. Please wait.
1
What is a virtual function?
2
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."
3
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."
4
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.
5
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."
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.