Static Data Member in C++ with Example
Description:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
#include <iostream> using namespace std; class A { private: int M,N; static int SS; public: A() { M=0; N=0; } void add(int x) { M=M+x; N=N+x; SS= SS+x; } void print(void) { cout<<" Value of M "<<M<<endl; cout<<" Value of N "<<N<<endl; cout<<" Value of SS "<<SS<<endl; } }; int A::SS=0; int main() { A aa,bb,cc; aa.add(2); aa.print(); bb.add(5); bb.print(); cc.add(3); cc.print(); } |
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.
Related Article:
https://programmingdigest.com/c-type-casting-explicit-and-implicit-with-examples/