How does a static member variable or static data member differs from a non-static variable or data? Explain with an example.



Static Data Member and Difference with Non-static Data Member: In general when we declare some objects of a class, each object is allocated with memory space for each variable of the class separately under them as given below,




But in the case of static data member only one memory location will be allocated and that will be used by all the objects of that class. Thus any object at any time can change the value of the static member by using it. It is something like the following,



So the main difference between a regular data member and a static data member is that each object will have different memory location for a single regular data member but each object will have a space in common for a static data member.

            Example: From the following given example of a program using static data member it can be seen that the two objects of the program is changing the regular variable of them separately but they are overwriting on the static data member.

//static data member
#include<iostream.h>

class shared{
 static int a;  //a is a static member
 int b;   //b is a regular member
 public:
  void set_ab(int i, int j){
   a=i;
   b=j;
   }
 void show();
 };

int shared::a;  //static a has been defined to use by class shared

void shared::show(){
 cout<<"Static a: "<<a<<"\n";
 cout<<"Non-Static b: "<<b<<"\n";
 }

void main(){
 shared x,y;  

 x.set_ab(1,1);  //setting 1 for a and 1 for b under object x
 x.show();
 y.set_ab(2,2);  //setting 2 for a and 2 for b under object y
 y.show();
 x.show();
 }

Output:
Static a: 1
Non-Static b: 1
Static a: 2
Non-Static b: 2
Static a: 2
Non-Static b: 1

From the output of the given program it can be understood that an object can affect the static member to change though it has been changed previously by another object. Here object ‘y’ is changing the static ‘a’ from 1 to 2 which was previously changed by ‘x’ from 0 to 1.  

Recommended Recommends

Comments

Contact Us