What is the static keyword in C++?

  • Static local variable: keeps its value between calls.
  • Static data member: one copy for the whole class.
  • Static member function: can be called without an object, and has no this.
  • Static at file level: the name is visible only in that file.
#include <iostream>

int next_id() {
    static int id = 0;           // set only once
    return ++id;
}

struct Counter {
    static inline int total = 0;
    Counter() { total++; }
};

int main() {
    std::cout << next_id() << next_id() << next_id() << '\n';
    Counter a, b;
    std::cout << Counter::total << '\n';
}
Output

123
2

See Static Members.


Learn more about the similar topics:
Tutorials
C++ Classes and Objects
C++ Constructors and Destructors
C++ Access Specifiers and Encapsulation
C++ Inheritance
C++ Polymorphism and Virtual Functions
C++ Abstract Classes and Interfaces
C++ Operator Overloading
Exercises & Assignments
Build a BankAccount class
Calculate areas with polymorphism
Overload operators for a Money class
Interview Questions & Answers
What is the difference between struct and class in C++?
What is a constructor in C++ and what are its types?
What is a destructor in C++?
What is the difference between overloading and overriding in C++?
What is a virtual function in C++?
What is a pure virtual function and an abstract class in C++?
What is the static keyword in C++?