c static variable

Posted under C++ Course On By mohammed.mutawe

c static variable

When static variables are dealt with in c++, the variable preserves the values ​​that are specified inside it throughout the life of the program during execution, and usually a flag is specified before the variable, which is static, for example, we create a variable of type static int val = 0, and that sign indicates the This variable is reserved in a special memory for static variables that take place throughout the life of the program without returning to the default value, and this is what distinguishes it from other types of variables.

 

Access

Programming languages ​​may differ in the ways to access static variables from inside the object, but in C++, the static variable inside the object is accessed by mentioning the name of the object (class) and placing two signs::, which are two vertical dots, and the static variable will appear to you automatically.

To simplify the idea a little, we will display a code for a counter inside the object that will automatically increment when defining any object of the same type, and to get a good idea, cancel static from the variable and notice the difference, then return it.

 

Example

Please, to understand the static variables well, copy the following code into your code editor.

#include<iostream>
using namespace std;
class mut {
private:
    static int count; int k;
public:
    mut() {
        count++; k = count;
    }
    int getcount() {
        return k;
    }
};
int mut::count = 0;
int main() {
    mut s1, s2, s3;
    cout << "Count is : " << s1.getcount() << endl;
    cout << "Count Is : " << s2.getcount() << endl;
    cout << "Count is : " << s3.getcount() << endl;
    return 0;
}

 

 

Leave a comment

Your email address will not be published. Required fields are marked *