Static Member Functions

Static member functions are considered to have class scope. In contrast to nonstatic member functions, these functions have no implicit this argument; therefore, they can use only static data members, enumerators, or nested types directly. Static member functions can be accessed without using an object of the corresponding class type. Consider this example:

class WindowManager
{
public:
    static int  CountOf();              // Return count of open windows.
           void Minimize();             // Minimize current window.
           WindowManager SideEffects(); // Function with side effects.
    ...
private:
    static int wmWindowCount;
};
int WindowManager::wmWindowCount = 0;

...

// Minimize (show iconic) all windows
for( int i = 0; i < WindowManager::CountOf(); ++i )
    rgwmWin[i].Minimize();

In the preceding code, the class WindowManager contains the static member function CountOf. This function returns the number of windows open but is not necessarily associated with a given object of type WindowManager. This concept is demonstrated in the loop where the CountOf function is used in the controlling expression; because CountOf is a static member function, it can be called without reference to an object.

Static member functions have external linkage. These functions do not have this pointers (covered in the next section). As a result, the following restrictions apply to such functions:

Note   The left side of a member-selection operator (. or –>) that selects a static member function is not evaluated. This can be important if the function is used for its side effects. For example, the expression SideEffects().CountOf() does not call the function SideEffects.