class Foo
{
public:
static int numFoos;
Foo() { numFoos++; }
~Foo() { numFoos--; }
};
int Foo::numFoos = 0;
In the above example, we declare "numFoos" to be a static member of
class Foo. When a member variable is declared static, it means that
there is only one instance of that variable for all instances
of the class. This means that the numFoos member of any object of
type Foo will be the same. One of the most common (and easily
understood) uses for this is to implement a counter for the number of
instantiated objects, which is what the Foo example does. Every time
a new Foo is created, numFoos is incremented. Every time a Foo is
destroyed, numFoos is decremented. In this way, the numFoos member
always stores the number of Foos in existence.
class Foo
{
public:
Foo() { numFoos++; }
~Foo() { numFoos--; }
static int getNumFoos() { return numFoos; }
static void resetNumFoos() { numFoos = 0; }
private:
static int numFoos;
};
int Foo::numFoos = 0;
Foo myFoo; cout << "Num foos = " << myFoo.getNumFoos() << endl;or
cout << "Num foos = " << Foo::getNumFoos() << endl;For non-static member functions, there is no method of calling a function equivalent to the second example here.
void myFunction()
{
static int numCalled = 0;
... // Does some stuff
numCalled++;
cout << "Function myFunction has been called " << numCalled
<< " times." << endl;
}
demonstrates a simple (and sometimes useful) reason to use a static
variable.© 2003 UC Riverside Department of Computer Science & Engineering. All rights reserved.