Simple Program for Static Data Members Using C++ Programming


Each object of a class has its own copy of all the data members of the class. In certain cases, all objects of a class should share only one copy of a variable. A static data member is used for these reasons.

  • − There is only one copy of a static data member is created for a class & is shared by all the objects of that class, no matter how many objects are created.
  • − The static data member doesn't participate in the size of an object.
  • −The static data member is also called as a class variable.
  • − There can be any number of static data members per class.
  • − Static data members are used to maintaining class-wide information

Simple Program for Static Data Members Using C++ Programming

#include<iostream> using namespace std; int main(){ class Demo_Static_Members{ static int a; //declaration public: void incr(); void print(); }; int Demo_Static_Members :: a; //Must be defined in this manner(by default initialized to zero) void Demo_Static_Members :: incr(){ a++; } void Demo_Static_Members :: print(){ cout<<a<<endl; } int main(){ Demo_Static_Members st1,st2,st3; st1.incr(); st2.incr(); st1.print(); st2.print(); st3.print(); return 0; }

Output:-

2
2
2

Explanation of the program

Even though a is being accessed in the incr() function & print() member functions, a doesn't belong to any of the objects. Only one copy of a is created. Accessing a in an ordinary member function is misleading that we are accessing a particular object's a. To avoid this confusion, we use static member function for accessing static data members. Static data members must be defined outside the class. It indicates two facts: The memory space for data is allocated only once before the program starts executing. There is only one static member variable for the class, each object does not have its own version of the variable