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 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

#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 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

This article is written by our awesome writer
Comments to: Static Data Members in C++ with Example

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password