C++ : Static Member

Static members

Whenever an object is declared separate copies of all the data elements are created for all the objects. Some times we need a data element which is present for all the objects of the class i.e. it is common for all the objects. Such variables are also known as class variables. The variables declared as static become the class variables.

Static variable/members are of two types:

* Static data elements
* Static member functions

Static data elements

* Static variables are declared using the keyword “static”.
* By default value of static data elements/variables is zero (0).
* Static variables are global in nature
* There is only one copy of static data elements and this copy is shared by all the objects of the class.
* The value of static data elements is available for all the objects of the class. It can be modified by any of the objects and the modified value will be present for all the objects of the class.
* The access rules for the static data elements is the same as that for normal data elements i.e. if it is declared in private then it cannot be accessed directly from outside the class.
* Static data elements have to be defined before the main function block.

Examples:

class sample
{
private:
static int a;
int roll;
char name[20];
public:
void read();
void show();
};
sample s1,s2,s3;

A static data element must be defined out side the class.

Example:
int sample::a;
or
int sample::a=100;

Number Of Visitors

0125737