© Slobodan Dmitrović 2020S. DmitrovićModern C++ for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-6047-0_27
The static specifier
says the object will have a static storage duration
. The memory space for static objects is allocated when the program starts and deallocated when the program ends. Only one instance of a static object exists in the program. If a local variable is marked as static, the space for it is allocated the first time the program control encounters its definition and deallocated when the program exits.
To define a local
static variable inside a function we use:
static int x = 0; // defined only the first time, skipped every other // time
std::cout << x << '\n';
myfunction(); // x == 1
myfunction(); // x == 2
myfunction(); // x == 3
This variable is initialized the first time the program encounters this function. The value of this variable is preserved across function calls. What does this mean? The last changes we made to it stays. It will not get initialized to 0 for every function call, only the first time.
This is convenient as we do not have to store the value inside some global variable x.
We can define static class member fields. Static class members are not part of the object. They live independently of an object of a class. We declare a static data member
inside the class and define it outside the class only once:
static int x; // declare a static data member
int MyClass::x = 123; // define a static data member
MyClass::x = 456; // access a static data member
std::cout << "Static data member value is: " << MyClass::x;
Here we declared a static data member inside a class. Then we defined it outside the class. When defining a static member outside the class, we do not need to use the static specifier. Then, we access the data member by using the MyClass::data_member_name notation.
a static member function, we prepend the function declaration with the static
keyword. The function definition outside the class does not use the static
static void myfunction(); // declare a static member function
// define a static member function
std::cout << "Hello World from a static member function.";
MyClass::myfunction(); // call a static member function