3 out of 3 rated this helpful - Rate this topic

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:

// static_member_functions.cpp
#include <stdio.h>

class StaticTest
{
private:
    static int x;
public:
    static int count()
    {
        return x;
    }
};

int StaticTest::x = 9;

int main()
{
    printf_s("%d\n", StaticTest::count());
}
9

In the preceding code, the class StaticTest contains the static member function count. This function returns the value of the private class member but is not necessarily associated with a given object of type StaticTest.

Static member functions have external linkage. These functions do not have this pointers. As a result, the following restrictions apply to such functions:

  • They cannot access nonstatic class member data using the member-selection operators (. or –>).

  • They cannot be declared as virtual.

  • They cannot have the same name as a nonstatic function that has the same argument types.

    Note 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.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
The Note in the documentation is wrong
The note says:
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.
This is just plain wrong. MSVC++ does call SideEffects() in this case, and by doing that it conforms to the C++ standard, which, in 9.4/2, clearly says that when using the class member access syntax (5.2.5) the object-expression shall be evaluated.