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."">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

What is a virtual function?

Similar presentations


Presentation on theme: "What is a virtual function?"— Presentation transcript:

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."


Download ppt "What is a virtual function?"

Similar presentations


Ads by Google