Static Data Member in C++ with Example

static data member

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:

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

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: