Virtual Functions-huh?

Started by
3 comments, last by Gimli 22 years, 8 months ago
Hey, I was reading "Sams Teach Yourself C++ in 21 days" and doing fine untill the middle of day 11 when they start talking about virtual functions. Could sommeone please explain them to me and tell me what there used for. Thank you.
Advertisement
A virtual function is a function which can be overridden in a child class. Now because that''s a horrible description, here''s some code to make it a bit clearer, in the context of an RPG-type game:
  class Monster{public:    virtual void attack();};class Ogre : public Monster{public:     void attack();};class Troll : public Monster{public:   void attack();};  

So, we have a base Monster class, and two derived classes which represent specific types of monsters. Each monster has a separate type of attack.
  Monster* currentMonster;currentMonster = new Ogre;currentMonster->attack();delete currentMonster;currentMonster = new Troll;currentMonster->attack();  

... and that''s what''s so special about virtual functions. You have a pointer to a Monster. You call the attack() function. But depending on what currentMonster actually points to, a different function will be called. If it points to an Ogre, the Ogre''s attack function gets called. If it points to a Troll, the Troll''s attack function gets called.

~~~~~~~~~~
Martee
ReactOS - an Open-source operating system compatible with Windows NT apps and drivers
Even though this thread has been up for a few hours, it has yet to garner a reply.

I would venture that this is the reason why: I made a similar post a few weeks ago titled "Virtual Functions? Inheretince? Why use them?". Quite a few people gave me very useful replies. Perhaps you should search for it.

-------------------------------
"A promise to a woman is just a lie that hasn''t happened yet."
-Mr. Floppy
------------------------------"I do not feel obliged to believe that the same God who has endowed us with sense, reason, and intellect has intended us to forgo their use. " - Galileo Galilei
I stand corrected

-------------------------------
"A promise to a woman is just a lie that hasn''t happened yet."
-Mr. Floppy
------------------------------"I do not feel obliged to believe that the same God who has endowed us with sense, reason, and intellect has intended us to forgo their use. " - Galileo Galilei


~~~~~~~~~~
Martee
ReactOS - an Open-source operating system compatible with Windows NT apps and drivers

This topic is closed to new replies.

Advertisement