I am trying to find dynamically and statically instantiated objects number. I am getting errors that variable myheap is not declared.
#include<iostream.h>
#include<stdlib.h>
class A {
public:
static int x; //To count number of total objects. incremented in constructor
static int myheap; //To count number of heap objects. Incremented in overloaded new
void* operator new(size_t t) {
A *p;
p=(A*)malloc(t);
myheap++;
return p;
}
void operator delete(void *p) {
free(p);
myheap--;
}
A() {
x++;
}
~A() {
x--;
}
};
int A::x=0;
int A::myheap=0;
int main() {
A *g,*h,*i;
A a,c,b,d,e;//Static allocations 5
g= new A();//Dynamic allocations 3
h= new A();
i= new A();
cout<<"Total"<<A::x<<'\n';
cout<<"Dynamic";
cout<<'\n'<<"HEAP"<<A::myheap;
delete g;
cout<<'\n'<<"After delete g"<<A::x;
cout<<'\n'<<"HEAP"<<A::myheap;
delete h;
cout<<'\n'<<"After delete h"<<A::x;
cout<<'\n'<<"HEAP"<<A::myheap;
delete i;
cout<<'\n'<<"After delete i"<<A::x;
cout<<'\n'<<"HEAP"<<A::myheap;
}
Your code is almost correct, but you’re seeing errors about ‘myheap’ because the compiler was confused about earlier errors. Fix the first error first.
About overloading operator new, there’s more to it than a simple malloc. I have an previous example that may help, but that was global new instead of class-specific.
Here it is cleaned up: (this compiles and runs)