- 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
Complete explanation of static data members with classes and program go to link :-
ReplyDeletehttp://geeksprogrammings.blogspot.in/2013/09/static-data-members.html