It's useful if you're going to make polymorphic classes.
If you've done any Windows programming I'm sure that you've read that everything on the screen is a window (duh, right) Even the scroll bars, the menu bars, text boxes buttons etc. are considered windows as far as the OS is concerned. It just sends generic messages to these 'windows' and doesn't care what they do with them. As far as it's concerned they're identical, even though we can tell they're vastly different.
Although Windows isn't written in C++ the concept is the same. In game programming a good example would be some arcade game where the entities perform vastly different and custom actions (i.e. one bad guy dies and explodes into four midget versions of himself that attack you, another makes one last death throw attack at you, another just dies) where it doesn't make sense to just create flags for each unique action. You can make a virtual bad guy class:
class generic_bad_guy{public: generic_bad_guy(); virtual ~generic_bad_guy(); // this should always be virtual for a base class virtual void actionDead(void) = 0; // pure virtual function, doesn't even exist}
And a few classes based on this:
class bad_guy_1 : public generic_bad_guy{public: virtual void actionDead(void){explode();}}class bad_guy_2 : public generic_bad_guy{public: virtual void actionDead(void){attack_one_more_time();}}
Of course you're probably saying "i could do that anyway, with inheritance", but you couldn't do this:
generic_bad_guy* badGuys[3];badGuy[0] = new bad_guy_1;badGuy[1] = new bad_guy_2;badGuy[2] = new bad_guy_3;//here's where it gets really crazyfor(int i = 0; i < 3; i++){ badGuy->actionDead();<BR>}<BR></pre><P>In an array or linked list, it doesn't care what type of bad guy it really is, it just calls the appropriate function at run-time and does completely different things.<P>Polymorphism isn't useful for everything, but when it is you can really start to kick out the wu-tang style in your code. <BR>
-the logistical one-http://members.bellatlantic.net/~olsongt