Four jobs for one keyword
The static keyword does four separate jobs in C++:
- Limit a name to its file. A function or variable declared
staticat file scope is visible only in that source file. - Keep a value between calls. A
staticlocal variable is set up once and keeps its value after the function returns. - Share one copy across objects. A
staticdata member belongs to the class, so every object sees the same variable. - Use a function without an object. A
staticmember function can be called through the class name.
One program, four uses
This program shows all four jobs in one place:
#include <iostream>
// 1. File scope: visible only in this source file.
static int twice(int x) {
return 2 * x;
}
class Tally {
public:
Tally() { ++created; }
// 4. Static member function: called without an object.
static int limit() { return 100; }
// 3. Static data member: one copy for all Tally objects.
static int created;
};
// The out-of-class definition is required; C++17 can use inline static instead.
int Tally::created = 0;
int next_number() {
// 2. Static local variable: keeps its value between calls.
static int calls = 0;
++calls;
return calls;
}
int main() {
std::cout << twice(4) << '\n'; // prints 8
std::cout << Tally::limit() << '\n'; // prints 100
Tally a;
Tally b;
std::cout << Tally::created << '\n'; // prints 2
int first = next_number();
int second = next_number();
std::cout << first << ' ' << second << '\n'; // prints 1 2
}
Why one word does several jobs
The meaning of static depends on where it appears:
| Where it appears | What it does |
|---|---|
| Outside any function or class | Limits the name to its source file |
| On a variable inside a function | Keeps the value for the whole program run |
| On a data member inside a class | Gives one copy shared by all objects |
| On a function inside a class | Makes the function belong to the class, not to an object |
What static does not do
- It does not make a value constant. A
staticvariable can change. For values that should never change, the C++ const keyword states that intent more clearly. - It is not the same as static typing. The word “statically” in “statically typed” refers to compile-time type checking, not to this keyword.
- It is not identical in every language. Java and C# also use
staticfor class members, but the rules differ in the details.
Choosing static
The first two jobs also work in C, because C has file-scope static and static local variables. The last two need classes, which C does not have.
Use static when one of those jobs is what you need. If none of them fits, leave the keyword out. For more specific guidance, see when should you use static.