Home »
C++ programming language
C++ - Count the number of objects using Static member function
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:
Counting the number of objects using Static member function
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 number of objects using Static member function
#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
Explanation
In above example, count is a static data member, which is incremented in constructor, thus, we can easily get the object counter.