Static Data member Like static variables, we can also define static data members of a class. the keyword static is used before the data member of a class. the characteristics of a static data member are the same as ordinary static variables. Its scope is within the class in which it is defined. Its lifetime starts when the object of the class (that contains the data member) is created and ends when the program is terminated.
For many objects of a class, there is only one static variable, which is created in the memory. If the value of static data members is changed in one object of the class, this value can be accessed from other objects. So data of static data members can be shared among all the objects of the same class. the static data members must also be declared and initialized after defining the class.
Programming example: write a program that explains the concept of the static data member of a class:
using namespace std;
static int SS;
void add(int x)
cout<<" Value of M "<<M<<endl;
cout<<" Value of N "<<N<<endl;
cout<<" Value of SS "<<SS<<endl;
In this program, class A is defined which contains a static data member ‘SS’. This class has two member functions ‘add’ and ‘print’. The ‘add’ function uses one argument. The value of the argument is added to the previous values of data members. The ‘print’ function is defined to print the values of data members.
The class has one constructor. The value 0 is initialized to data member ‘M’ and ‘N’ through this constructor. The statement “int A::ss= 0;” is written after the class definition. This statement must be written to declare and initialize the static data member of the specified class.
Three objects ‘aa’, ‘bb’ and ‘cc’ are declared of the class A. the ‘add’ function is called for the object ‘aa’ to add value 2 to all data members of the class. the values of data members are printed through ‘print’ function. The ‘add’ function (with different data value) and ‘print’ function are also called for the objects ‘bb’ and ‘cc’. the data values of data members in memory are shown in the following figure.
Please note that the contents of “SS” are incremented with a specified value. the data member “SS” is created only in one memory location and all objects of the class can share its data. The positions of objects ‘aa’, ‘bb’ and ‘cc’ and data member ‘SS’ in memory is shown in the following figure.