The static keyword can be used in four different ways:
Static local variables keep their value between function calls. For example, in the following code, a static variable inside a function is used to keep track of how many times that function has been called:
void foo() { static int counter = 0; cout << "foo has been called " << ++counter << " times\n"; } int main() { for( int i = 0; i < 10; ++i ) foo(); }
When used in a class data member, all instantiations of that class share one copy of the variable.
class Foo { public: Foo() { ++numFoos; cout << "We have now created " << numFoos << " instances of the Foo class\n"; } private: static int numFoos; }; int Foo::numFoos = 0; // allocate memory for numFoos, and initialize it int main() { Foo f1; Foo f2; Foo f3; }
In the example above, the static class variable numFoos is shared between all three instances of the Foo class (f1, f2 and f3) and keeps a count of the number of times that the Foo class has been instantiated.
When used in a class function member, the function does not take an instantiation as an implicit this parameter, instead behaving like a free function. This means that static class functions can be called without creating instances of the class:
class Foo { public: Foo() { ++numFoos; cout << "We have now created " << numFoos << " instances of the Foo class\n"; } static int getNumFoos() { return numFoos; } private: static int numFoos; }; int Foo::numFoos = 0; // allocate memory for numFoos, and initialize it int main() { Foo f1; Foo f2; Foo f3; cout << "So far, we've made " << Foo::getNumFoos() << " instances of the Foo class\n"; }