When I use virtual destructor of struct M, operator new after delete operator return point to other address.
struct M {
virtual ~M() = default;
};
struct D : public M {
int* b = nullptr;
};
struct C : public M {
int* c = nullptr, *b = nullptr;
long d = 10;
};
int main() {
M* f;
M* d;
f = new D;
static_cast<D*>(f)->b = new int(10);
std::cout << f << ":" << sizeof(*f) << std::endl; // 0x23c1c20 : 8
delete f;
d = new C;
std::cout << d << ":" << sizeof(*d) << std::endl; // 0x23c2c70 : 8
delete d;
return 0;
}
But if destructor of struct M is non-virtual operator new return same address.
struct M {
~M() = default;
};
...
int main() {
M* f;
M* d;
f = new D;
static_cast<D*>(f)->b = new int(10);
std::cout << f << ":" << sizeof(*f) << std::endl; // 0x23c1c20 : 1
delete f;
d = new C;
std::cout << d << ":" << sizeof(*d) << std::endl; // 0x23c1c20 : 1
delete d;
return 0;
}
And the size of the objects is different.
Why is this happening?