Static
data members are useful because they work for the class as a whole, and not for
a particular instance/object of a class. One effect of a static data member is
that it doesn't occupy space in each object, so the size of each object is
reduced.
Although
member functions don't occupy space in an object, when a function is called
that function must somehow know which object data it is accessing. This is done
by the compiler, secretly, by passing the starting address of the object into
the member function. You can access the starting address while inside the
member function using the keyword this. The extra overhead of the member
function call when passing this is analogous to the extra size in an object
when adding data members. In line with this analogy, you can remove the extra
time involved in a member function call by making the member function static.
Like
a static data member, a static member function acts for the class as a whole,
not for a particular object of the class. The starting address of the object
(this)
is not passed to a static member function, so it cannot access non-static data
members (and the compiler will give you an error if you try). The only data
members which can be accessed by a static member function are static data
members.
You
can call a static member function in the ordinary way, with the dot or the
arrow, in association with an object. However, you can also call a static
member function by itself, without any specific object, using the
scope-resolution operator, like this:
class X {
public:
static void f();
};
X::f();
When
you see static member functions in a class, remember that the designer intended
that function to be conceptually associated with the class as a whole. That
function will have the faster calling time of an ordinary, global function but
its name will be visible only within the class, so it won't clash with global
function names.