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}