devxlogo

Counting “Live” Instances of a Class

Counting “Live” Instances of a Class

Counting the number of object instances of a certain class can be necessary in debugging and performance tuning. To do that, declare a static data member as a counter, and have the constructor and copy constructor increment it and the destructor decrement it. Finally, add a static member function that returns the current instance count:

 class A{private: static int count;public: A() { ++count;} A(const A& rhs) { ++count;} ~A() {--count;}public: static int get_count() {return count;}};int A::count; //definition of static member

Because static members are automatically zero-initialized, you can call this function and get the correct results even if there’s not a single instance of that class at that time:

 int main(){ int n = A::get_count(); // 0 A a; n = A::get_count(); // 1 A * p = new A(a); n = A::get_count(); // 2 delete p;  n = A::get_count(); // 1}
See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist