I have come across a bizarre problem and I have created this simple program in order to demonstrate it. I know the code itself doesn't make much sense, but I would like to highlight something I don't understand.
#include <iostream>
using namespace std;
class tempClass{
public:
float n;
tempClass(){};
~tempClass(){} //VERY IMPORTANT LINE
void* operator new[](size_t size);
};
void* tempClass::operator new[](size_t size){
tempClass* a;
a= ::new tempClass[2];
for (int i = 0; i < 2; i++)
{
a[i].n = i*10;
}
cout << a << endl;
return a;
}
int main(){
tempClass* a;
a = new tempClass[2];
cout << a << endl;
cout << a[0].n << endl;
return 0;
}
In the code, I have overloaded the operator new for the class that I have created. However, the behaviour of the function changes, depending on whether I include the destructor of the class or not. I have noticed, that if I don't include the destructor, everything works fine, whereas if I did, the returned value of the pointer a
would be increased by 8
at all times. Therefore, in this example, the last cout
of the program will print 20
if I include the destructor and 0
if I don't, at all times. Why does this happen?