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.
Question (easy): What would be the result of making "getNumFoos()" and
"resetNumFoos()" non-static in the above example?
Question (hard): Why can you not call Object::function() for
non-static functions? (HINT: Try to think like the compiler, knowing
that you have to prevent any problems at compile time.)