In your code, call the function as follows:
Thing t;
...
x = t.get_count(); // get the count
x = Thing::get_count(); // get the count
The function get_count is a static member function that returns the value of the static member
variable count. Because it is static, it can be called either with or without an object being involved. If
it is called with an object, as in t.get_count(), the only role that object "t" plays is to inform the
compiler what class get_count belongs to. As with static member variables, accessing a static
member function through an object is not usually done. Normally, the class scope operator form is
used to call a static member function.
An important property of a static member function is that you can't access the ordinary (non-static)
members of the class from within the static member function - there is no individual object
automatically involved (there is no "this" object). If you need your static member function to access
the members of an object in its class, you have to pass in the object as a parameter of some sort, or
provide some other access (e.g. through a global variable or static member variable). Because the
static member function is a member of the class, it can then access all members of the passed-in
object.
Summary
A static member variable:
• Belongs to the whole class, and there is only one of it, regardless of the number of objects.
• Must be defined and initialized outside of any function, like a global variable.
• It can be accessed by any member function of the class.
• Normally, it is accessed with the class scope operator. If it is private, use a static member function
to read or write it.
A static member function:
• Is like an ordinary non-member function, but its scope is the class.
• It can access all members of an object in its class, but only if you make the object available, such
as in a parameter - there is no "this" object.
• Normally, it is called with the class scope operator.
Tip: If you get a linker error complaining about an undefined static member variable, it means you
forgot the line of code that defines and initializes it. Like ordinary member variables, the appearance
of the variable in the class declaration is just a declaration; no actual variables in memory are created
by the declaration. A static member variable thus comes into existence when you define it in the
initialization line. This is a common error; after making it a few times, you'll recognize it!
Note: Standard C++ allows you to initialize a static member from within the class declaration (see
Stroustrup, 10.4.6.2), but it only works for const int static member variables, and the initializing
expression must be a constant itself. Because this special case is only occasionally useful, I've
adopted a uniform policy of initializing static members outside of the class declaration, as described
in this handout.