Static class members are data and functions that are associated with the class itself, rather than with the objects of the class. In the following example, class Fred has a static data member x_ and an instance data member y_. There is only one copy of Fred::x_ regardless of how many Fred objects are created (including no Fred objects), but there is one y_ per Fred object. Thus x_ is said to be associated with the class and y_ is said to be associated with an individual object of the class. Similarly class Fred has a static member function f() and an instance member function g(). class Fred { public: static void f() throw(); <-- 1 void g() throw(); <-- 2 protected: static int x_; <-- 3 int y_; <-- 4 };
Everything except instance data members must be defined somewhere, such as in the Fred.cpp source file: #include "Fred.hpp" void Fred::f() throw() <-- 1 { /*...*/ } void Fred::g() throw() { /*...*/ } int Fred::x_ = 3; <-- 2
Static data members are often referred to as class data, and static member functions are often referred to as class services or class methods. |