Summary: In this tutorial, we will discuss with the example what is a static variable in C++, how to declare, and when to use a static variable in our program.
What is Static Variable?
A variable, when declared following the ‘
static‘ keyword, becomes a static variable.
static <type> <variable_name>;
If a static variable is declared:
- Inside a class then all the instance of the class (i.e. object) shares the same copy of the variable. Also the variable can be accessed directly with class name.
- Inside a function then its value is preserved between successive calls to that function for the lifetime (program) but cannot be accessible outside the scope or function in which it has been declared.
Let’s see examples of both types of static variables in C++.
Example 1: Static Variable inside of a Class
using namespace std;
static int num;
//It is important to initialize the static variable outside of a class
//So, redeclare it by pointing with the help of class name.
int Natural::num = 0;
//Creating 1st object
//Incrementing Natural::num 2 times
cout << "Num of 1st Object: "<< obj1.num << endl;
//Creating 2nd object
cout << "Num of 2nd Object: "<< obj2.num << endl;
Num of 1st Object: 2
Num of 2nd Object: 2
Notice, we have created an object of
Natural class and used
incerase() method to increment the value of
num two times and then again we created another object of the same class but this time we didn’t call the
incerase() method but output the value of
The value of num in both objects is 2, which proves that a static variable is shared among the objects.
Example 2: Static Variable inside a Function
using namespace std;
static int num = 0;
cout << ++num << endl;
Notice the output in this case. We have called the increase function in the main two times and on the second call, the output is the incremented value of the initial value of the first
increase() function call.
This proves that the static variable inside a function is declared only once on the first function call and the rest of the successive function calls use the same copy.
When to use Static Variable in C++?
- When you want to use old value of variable (last function call) into the current function call. (like Example 2)
- When you want to share same copy of the variable in class among all its objects.
In this tutorial, we learned what is a static variable, what is it significance in C++, and when to use static variable in C++.