Implement an objects counter mechanism for a class in C++

(Last Updated On: February 11, 2017)

Interview question: Can you implement an object counter program in C++ for a class that count the number of objects created for that class.

Answer: Actually, counting object in C++ implementation is simple.

Solution is, to create a static variable, say “objCount” and a static method like “GetObjectCount()” that returns number of objects created for the class.

[Why static variable & static method in C++? – Since, a static variable is shared by all the instances of the class, all the objects will increment the persisting value of “objCount”. And a static method, so, we can call by class name not by using any instance of the class.]

Secondly, we have to increment objCount in class constructor and copy constructor and decrement it into class destructor.

Example:

 

Output:

Test object counter…

Number of objects alive so for : 4

Number of objects alive so for : 3