Table of Contents

static

The static keyword can be used in four different ways:

  1. to create permanent storage for local variables in a function,
  2. to create a single copy of class data,
  3. to declare member functions that act like a non-member functions, and
  4. to specify internal linkage.

Permanent storage

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();
}

Single copy of class data

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.

Class functions callable without an object

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";
}

Internal linkage

When used on a free function, a global variable, or a global constant, it specifies internal linkage (as opposed to extern, which specifies external linkage). Internal linkage limits access to the data or function to the current file.

Related: extern