That snarky response seems a bit rough! MSDN is great but I often find it hard to learn much about the hows and whys of use from it.
I've found static data members in classes to be very useful in providing an interface between class member functions and global variables. Without them, in order to make data available for use in a member function I would have to either pass it (or a pointer to it) as an argument in a function call OR make it a data member of the class then keep every instances copy of the value updated. The first (passing as argument) makes writing virtual functions a nightmare. This is because all such functions must have identical parameter lists - I have to pass all data to each that any one might need. The second method (adding data members) is often wasteful because I'm creating many copies of the same value.
Example: In a space shooter video game several enemy ship classes are derived from a base ship class. Some ships fire aimed shots, others don't. Some ships fire different types of shots. I would like to have a virtual function for firing shots which can be called like this:
pShip->fire()
where pShip may be pointing to an instance of any ship class.
The fire() needs a pointer to an array of shots for firing, the size of this array, an instance of a shot to serve as a template for initializing the fired shots data members and maybe the targets coordinates. All virtual versions of fire() have access to all this as common data because of static data members in the base class:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class ship
{
// static dms
static cvShot* p_cvDump;// pointer to ammo dump (array of constant velocity shots)
static int cvDumpsz;// size of this array
static float tposx;// target position maintained under WM_MOUSEMOVE
static float tposy;
static cvShot* p_cvTemplates;// templates for fired shots
static int NcvTemplates;// size of template array
static int playerScore;// a member function can update this value when a ship is killed
static int numKills;// this one too
// more stuff
}
|
Those last two (playerScore, numKills) enable simplification of the game logic. When the function
pShip->check4Hit()
determines a kill has been made, these values are automatically updated like so:
1 2 3 4 5 6 7 8 9 10
|
ship::check4Hit()
{
// a bunch of other code
if( hitsLeft <= 0 )// that was a kill
{
inPlay = FALSE;
playerScore += scoreValue;// static
numKills += 1;// ship class variables
}
}
|
I hope the examples given were sensible.