Archived

This topic is now archived and is closed to further replies.

Virtual Functions-huh?

This topic is 5965 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites