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:
- It will initialize to zero when the first object in its class is created. No additional initialization is allowed.
- Only one copy of this member is created for the entire class and is shared by all objects in that class, regardless of the number of objects created.
- It is only visible within the class, but its lifespan is the whole program.
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:
