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:
#include using namespace std; class A{ static int objCount; // counter to count the object public: A() { ++objCount; } A(const A &a) { ++objCount; } ~A() { --objCount; } /* Retruns the number of objects created for this class*/ static int GetObjectCount() { return objCount; } //other methods void MethodOne(){ cout<< "Method Two..."<<"\n"; } void MethodTwo(){ cout<< "Method Two..."<<"\n"; } }; int A::objCount = 0; // initialize static variable int main(){ cout<< "\nTest object counter..."<<"\n"; A obj1; // statically created object A obj2; A *obj3 = new A(); //dynamically created object A *obj4 = new A(); cout<< "\nNumber of objects alive so for : "<< A::GetObjectCount()<<"\n"; delete obj3; delete obj4; A obj5 = obj1; // invokes copy constructor cout<< "\nNumber of objects alive so for : "<< A::GetObjectCount()<<"\n"; return 0; }
Output:
Test object counter…
Number of objects alive so for : 4
Number of objects alive so for : 3