Ceoddyn has the right idea. When you declare a function as virtual, it gets added to the class's virtual function table. This little table creates a level of indirection allowing you to assign a call to that function to any function by that name, regardless of where it falls in the inheritance chain, simply by changing which interface you're addressing. The best way to explain perhaps is to use an example.
class Item{public: virtual UseItem() { cout << "You eat/drink the item." << endl; }};class Weapon : public Item{public: virtual UseItem() { cout << "You wield the weapon." << endl; }};Now, if I create an object of type "Weapon" such as the line below and call UseItem it calls the function as normal.// This does exactly what you expectWeapon* pWeapon = new Weapon();pWeapon->UseItem();Where it's different, is if I've got a pointer which claims to be a different interface than the object actually is..for exampleItem* pItem = pWeapon; // assign the weapon to the item pointer, since a weapon IS-A item this is perfectly legal.// Here's the magic of virtual functions. When I call UseItem on this pointer// i see "You wield the weapon." because pItem ACTUALLY points to a weapon,// and since the function is virtual, the correct call is resolved.// if the function UseItem had not been virtual, it would not have been able// to resolve the call to the correct type, and I would have seen // "You eat/drink the item." instead.pItem->UseItem();
Give it a try, you'll see for yourself.
Cheers!