< Previous | Contents | Next >
You can access a public static data member anywhere in your program. In main(), I access Critter::s_Total with the following line, which displays 0, the value of the static data member and the total number of Critter objects that have been instantiated.
cout << Critter::s_Total << "\n\n";
Hi n t
You can also access a static data member through any object of the class. Assuming that crit1 is a Critter object, I could display the total number of critters with the following line:
cout << crit1.s_Total << "\n\n";
I also access this static data member in the Critter constructor with the following line, which increments s_Total.
++s_Total;
Using Static Data Members and Member Functions 273
This means that every time a new object is instantiated, s_Total is incremented. Notice that I didn’t qualify s_Total with Critter::. Just as with non-static data members, you don’t have to qualify a static data member with its class name inside its class.
Although I made my static data member public, you can make a static data member private—but then, like any other data member, you can only access it in a class member function.