Static Data Members in C++
A data member of a class can be qualified as static (storage-class). The properties of a static member variable are similar to that of a C static variable. Read more about storage classes in C (Click here)
In addition, a static member variable (of a class) has certain special characteristics which are detailed as follows:
- 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 records the occurrences of all the objects. Program given below illustrates the use of a static data member.
#include <iostream.h> class item { private: static int count; //count is STATIC int number; public: void getdata(int a) { number = a; count++; } void getcount() { cout << "Count :" << count << endl; } }; int item::count; //count DEFINED void main() { item a, b, c; //count is initialized to zero a.getcount(); //display count b.getcount(); c.getcount(); a.getdata(100); //getting data into object a b.getdata(220); //getting data into object b c.getdata(550); //getting data into object c cout << "After reading data" << endl; a.getcount(); //display count b.getcount(); c.getcount(); }
The output of the above program would be:
count: 0 count: 0 count: 0 After reading data count: 3 count: 3 count: 3
In the given program:
- Notice the following statement:
int item::count;
Note that the type and scope of each static member variable must be defined outside the class definition. This is necessary because the static data members are stored separately rather than as a part of an object. Since they are associated with the class itself rather than with any class objects, they are also known as class variable - The static variable count is initialized to zero when the first objects is created. The count is incremented whenever the data is read into an object. Since the data is read into object three times, the variable count is incremented three times. Because, there is only one copy of count shared by all the three objects, all the three output statements cause the value 3 to be displayed
- Static variables are like non-inline member functions in the sense that they are declared in a class definition and defined outside the source file