Objects: Static member functions:
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;
A static function is often useful when you want a function that
operates on static variables of a class, or that can operate when
there is no instance of the class. For example, with the above
version of Foo, either of the following will return the number of
objects with type Foo that have been created:
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.