I have written below program to count the number of static and dynamically created object of the class.
#include <iostream>
class Test
{
public:
Test()
{
stackCount++;
}
void* operator new(size_t objSize)
{
void* ptr = malloc(objSize);
heapCount++;
return ptr;
}
static void Display()
{
std::cout << "stack object count : " << stackCount - heapCount << ", Heap object Count :" <<
heapCount << std::endl;
}
private:
static int stackCount;
static int heapCount;
};
int Test::stackCount = 0;
int Test::heapCount = 0;
int main()
{
Test obj1;
Test obj2;
Test obj3;
Test *ptr = new Test();
Test::Display();
return 0;
}
Program output : stack object count : 3, Heap object Count :1
is there any better way to maintain the count of static and dynamic object.?