< Previous | Contents | Next >
Declaring and Initializing Static Data
A static data member is a single data member that exists for the entire class. In the class definition, I declare a static data member s_Total to store the number of Critter objects that have been instantiated.
static int s_Total; //static member variable declaration
You can declare your own static data members just like I did, by starting the declaration with the static keyword. I prefixed the variable name with s_ so it would be instantly recognizable as a static data member.
Outside of the class definition, I initialize the static data member to 0.
int Critter::s_Total = 0; //static member variable initialization
Notice that I qualified the data member name with Critter::. Outside of its class definition, you must qualify a static data member with its class name. After the previous line of code executes, there is a single value associated with the Critter class, stored in its static data member s_Total with a value of 0.
Hi n t
You can declare a static variable in non-class functions, too. The static variable maintains its value between function calls.