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

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.