Static data members or variables in C++

For a normal data member or a variable individual copies of variable are made for each object. However, a static data member has only one copy of the member and all other objects share that member. Every static variable is initialized to zero before any object is created. That means a static variable exists before any object of a class I created. There is no storage allocated for a static data member. It is defined as a global definition outside the class by using scope resolution operator to tell the compiler to which class it belongs. Static data member is used to grant access control to shared resources used by all objects of a class. It is also used to make a note of how many objects of a class exist.


static type name;

where, type is the data type of the variable and name is the name of the variable.

For Example:

class test {

static int x;

int y;

} ;

int test::x;

Leave a Reply