© Slobodan Dmitrović 2020
S. DmitrovićModern C++ for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-6047-0_27

27. The static Specifier

Slobodan Dmitrović1 
(1)
Belgrade, Serbia
 

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:
#include <iostream>
void myfunction()
{
    static int x = 0; // defined only the first time, skipped every other // time
    x++;
    std::cout << x << ' ';
}
int main()
{
    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:
#include <iostream>
class MyClass
{
public:
    static int x; // declare a static data member
};
int MyClass::x = 123; // define a static data member
int main()
{
    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.

To define a static member function, we prepend the function declaration with the static keyword. The function definition outside the class does not use the static keyword:
#include <iostream>
class MyClass
{
public:
    static void myfunction(); // declare a static member function
};
// define a static member function
void MyClass::myfunction()
{
    std::cout << "Hello World from a static member function.";
}
int main()
{
    MyClass::myfunction(); // call a static member function
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.32.116