Possible Duplicate:
Overriding vs Virtual
In C++, whether you choose to use virtual or not, you can still override the base class function. The following compiles just fine…
class Enemy
{
public:
void SelectAnimation();
void RunAI();
void Interact()
{
cout<<"Hi I am a regular Enemy";
}
private:
int m_iHitPoints;
};
class Boss : public Enemy
{
public:
void Interact()
{
cout<<"Hi I am a evil Boss";
}
};
So my question is what is the difference in using or not using the virtual function. And what is the disadvantage.
If you have the code:
and Interact is not virtual, you will get Enemy’s Interact. In other words, the function will be selected based on the apparent rather than its real type of the thing it is being called on. This is almost never what you want, so if you intend to call methods via a base pointer (for example, if you have a collection of base pointers in a vector or list) then the function should be made virtual in the base class. You will also need to make the destructor of such base classes virtual, so that the behaviour when deleting instances via a base pointer is well-defined.