Last updated on June 13th, 2020 at 08:34 pm
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,
//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();
}