What is the purpose of the static keyword in C++?
In C++, the static keyword has different roles depending on the context in which it is used.
- In the global context, the static keyword is used to restrict the scope of variables or functions. When the static keyword is used for global variables, it limits the scope of the variable to the current source file, preventing other files from accessing it. Similarly, when the static keyword is used for global functions, it limits the scope of the function to the current source file, preventing other files from directly calling it.
- In the context of classes, the “static” keyword is used to indicate static members of a class. These static members are shared by all objects of the class, rather than each object having its own copy. Static members can be static variables or static functions. Static variables have only one copy in memory, which is shared by all objects. Static functions can be called directly using the class name, without needing to create an object instance.
- Within the context of a function, the static keyword is used to indicate that the function’s lifespan is the same as the program’s lifespan. Once a function is declared as static, it will exist throughout the entire execution of the program, rather than being created and destroyed each time the function is called. Static functions can only access static variables.
In summary, the static keyword in C++ is used to restrict the scope of variables, functions, or class members, indicating static members and indicating the lifecycle of functions.