virtual function question

Started by
8 comments, last by geo2004 16 years, 9 months ago
I've got a quick question about virtual functions. I'm kinda rusty on them. Here's some quick pseudocode of what I have.

class Unit
{
   public:
        virtual void Think(){// move/attack/chase/etc.}
};

class Marine : public Unit
{

};

If I don't tell the Marine class what to do in Think(), it will automatically default back to the Unit class Think() function right? Therefore Unit can have Generic thinking, and each derived class has more specialized thinking, but only if it needs it. Jeff
Advertisement
Yes.
Yes*.

*: promotional offer only valid when the derived class does not define an override of the virtual function (as opposed to defining an empty override) and the virtual function in the base class is defined (as opposed to being pure virtual).
Yes.
So declaring an empty function will still default back to the base class, ie

class Marine : public Unit{   public :      void Think(){}       // <- this is ok and goes back to Unit?      void Think(){//bla} // <- this will override base function?};
Yes.

Quote:Original post by Toolmaker
Yes.
Wrong.

If you provide an implementation for a derived class (Your Marine class here), even an empty one, the base function (Unit::Think) will NOT be called. If you want to call it anyway, you can do:
class Marine : public Unit{   public :      void Think()      {         // Do any code here         Unit::Think(); // Call base class Think()         // Do any code here      }};
Quote:
So declaring an empty function will still default back to the base class, ie

class Marine : public Unit
{
public :
void Think(){} // <- this is ok and goes back to Unit?
void Think(){//bla} // <- this will override base function?
};

No, once you've declared the function in the derived class, you've overridden it. The base function must then be called explicitly if you still want to reuse its functionality.
void Think() { Unit::Think(); }

Quote:
Quote:
Original post by Toolmaker
Yes.

Wrong.

I suspect, given the post times, that he was attmpting to continue the "yes" streak...
A marine that can think on its own?! haha.

Anyhow, what you can possibly do in the derived Think() method is to simply call the base class method to transfer control to it using the scoping operator like so:

Unit::Think();

I obviously don't know the details of what you're doing, but hope that helps.

EDIT: well I was a bit late.
Ok, got it, I just wanted to make sure I was doing it correctly. Thanks for the help everyone!

Jeff

This topic is closed to new replies.

Advertisement