< Previous | Contents | Next >
Introducing the Static Critter
The Static Critter program declares a new kind of critter with a static data member that stores the total number of critters that have been created. It also defines a static member function that displays the total. Before the program instantiates any new critter objects, it displays the total number of critters by directly accessing the static data member that holds the total. Next, the program instantiates three new critters. Then it displays the total number of critters by calling a static member function that accesses the static data member. Figure 8.4 shows the results of the program.
Figure 8.4
The program stores the total number of Critter objects in the static data member s_Total and accesses that data member in two different ways.
You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 8 folder; the filename is static_critter.cpp.
//Static Critter
//Demonstrates static member variables and functions #include <iostream>
using namespace std;
Using Static Data Members and Member Functions 271
class Critter
{
public:
static int s_Total; //static member variable declaration
//total number of Critter objects in existence
Critter(int hunger = 0);
static int GetTotal(); //static member function prototype
private:
int m_Hunger;
};
int Critter::s_Total = 0; //static member variable initialization Critter::Critter(int hunger):
m_Hunger(hunger)
{
cout << "A critter has been born!" << endl;
++s_Total;
}
int Critter::GetTotal() //static member function definition
{
return s_Total;
}
int main()
{
cout << "The total number of critters is: "; cout << Critter::s_Total << "\n\n";
Critter crit1, crit2, crit3;
cout << "\nThe total number of critters is: "; cout << Critter::GetTotal() << "\n";
return 0;
}
272 Chapter 8 n Classes: Critter Caretaker