i2tutorials

CPP – Static Data member and its characteristics

Static Data member and its characteristics

 

A data member of a class can be referred to as static. The properties of a static member variable are similar to those of a C static variable.

The properties of static data member are:

Static variables are typically used to maintain values common to the whole class. The type and scope of each static member variable shall be defined beyond the class definition.

 

Static data members are defined outside of the class specification as

 data-type class-name::var-name=initial value;

This is required because static data elements are stored separately instead of as part of an object. 

Since they are associated with the class itself rather than its object, they are also known as class variables.

 

Example program:

#include <iostream>
using namespace std;
class Item
{
static int count;
public:
void display()
{
cout<<"Count = "<< ++count<<endl;
}
};
int Item :: count;
int main()
{
Item A;
A.display();
A.display();
return 0;
}

 

Output:

Exit mobile version