Static Data Members

A data member of a class can be qualified as static. The properties of a static member variable are similar to that of a C static variable. A static member variable has certain special characteristics. These are:
  • It is initialized to zero when the first object of its class is created. No other initialization is permitted.
  • Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.
  • It is visible only within the class, but its lifetime is the entire program.

Static variables are normally used to maintain values common to the entire class. For example, a static data member can be used as a counter that record the occurrences of all the objects.Program illustrates the use of a static data member.

#include
using namespace std;

class item
{
static int count;
int number;
public:
void getdata(int a)
{
number = a;
count ++;
}
void getcount(void)
{
cout << "Count: ";
cout << count <<"\n";
}
};
int item :: count;

int main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();

a.getdata(100);
b.getdata(200);
c.getdata(300);

cout << "After reading data"<<"\n";
a.getcount();
b.getcount();
c.getcount();
return 0;
}

The output of the program would be:
Count: 0
Count: 0
Count: 0
After reading data
Count: 3
Count: 3
Count: 3

1 comment:

  1. Complete explanation of static data members with classes and program go to link :-

    http://geeksprogrammings.blogspot.in/2013/09/static-data-members.html

    ReplyDelete