Static Data Member in C++ with Example

static data member


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:

#include <iostream>
using namespace std;
class A 
        int M,N;
        static int SS;
    void add(int 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;

static data member

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.

static data member

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.

static data member

Related Article:

C++ Type Casting: Explicit and Implicit with Examples

Related Articles

Leave a Reply

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

Back to top button