Home » C++ programming language

Demonstrate example of C++ static data member which counts total number of object created

C++ program to count total number of created objects through the static data member. Learn: how can we use class data member as a object counter?

Before moving ahead, I would recommend please read these two posts:

As we know that static members are class members. They are sharable for all objects in class. So we can count total number of objects using a counter, and the counter must be static data member.

C++ program to count the created objects

#include <iostream>
using namespace std;

class Counter
{
	private:	
	    //static data member as count
		static int count;

	public:
	    //default constructor 
		Counter()
		{ count++; }
		//static member function
		static void Print()
		{
			cout<<"\nTotal objects are: "<<count;
		}
};

//count initialization with 0
int Counter :: count = 0;

int main()
{
	Counter OB1;
	OB1.Print();
	
	Counter OB2;
	OB2.Print();
	
	Counter OB3;
	OB3.Print();
	
	return 0;
}

Output

Total objects are: 1
Total objects are: 2
Total objects are: 3

In above example, count is a static data member, which is incremented in constructor, thus, we can easily get the object counter.






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.