Static Variables in C++ (Static Data Members)

How Static Variables work in C++

Whenever you create a variable as static in C++, there would be only one single copy or memory allocated for the variable which will be shared throughout the code. There may the following examples of static variable application in C++ –

When static is implemented as a function

With each call of function() same alphabet memory copy is referenced each time and is incremented by 1 every time. This happens as alphabet is declared const and only gets initialised once and is re-used multiple times in every function call.

#include <iostream>

using namespace std;

void function()
{
// the initialisation only happens once
static char alphabet = 'a';
cout << alphabet << " ";

// the value here will be incremented to next ascii value
// ascii value of a is 97 doing ++ will incrment it to 98 which is ascii value of b
//a - z will be printed after each increment
//this value will be carried over to each implementation of function as alphabet is static variable
alphabet++;
}

int main()
{
int x = 26;
while(x--)
function();
return 0;
}

Output

a b c d e f g h i j k l m n o p q r s t u v w x y z

When implemented in a class in C++

If we create multiple objects to class and one of the data member of the class is declared static. In such case all the objects of the class will share the data member and only one single data member (variable) copy will be created at a single memory location

#include <iostream>
using namespace std;

class Student
{
public:
static int val; //static data member declaration

Student(){
/* We should not initialise static members of a class in a constructor
as they are not associated with each object of the class. It is shared by all objects.
*/
}
}; 

//static data members def must be outside the class
int Student::val=200;

main()
{
//student1.val,student1.val
Student student1, student2;

cout << "student1.val=" << student1.val << endl;
cout << "student2.val=" << student2.val << endl;

// student2.val,student1.val also becomes 500
student2.val=500;

cout << "\nstudent1.val=" << student1.val << endl;
cout << "student2.val=" << student2.val << endl;
}

Output

student1.val=200 
student2.val=200

student1.val=500
student2.val=500