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
	    //static data member as count
		static int count;

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

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

int main()
	Counter OB1;
	Counter OB2;
	Counter OB3;
	return 0;


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.

Related Tutorials

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.