Like other answers have indicated, if this works, it's by coincidence. By doing delete parent_ptr
, you're telling the compiler you want to delete something of type parent
, but since the constructor of parent
wasn't used to create/allocate this memory, this will result in undefined behavior.
But I'm wondering why you'd want to do this. Do you want to control where the memory of child
is allocated? To make that work, you would need to modify your code in a couple of ways:
- create
child
through its constructor
- overload
new
to fetch memory from where you want it (and if you're doing something special like fetch from a static buffer, overload delete
to handle delete correctly)
- make the destructor of
parent
virtual so child destructors are also called (even if you have upcasted)
The resulting code may look a bit like this:
struct parent
{
int i;
virtual ~parent()
{
printf("~parent()\n");
}
};
struct child : public parent
{
char value[1024*1024];
// you probably also want to overload operator new[]
void * operator new (std::size_t size)
{
return new char[size];
}
~child()
{
printf("~child()\n");
}
};
int main()
{
parent * p = new child(); // no need to cast here (obviously)
delete p;
return 0;
}
which prints:
~child()
~parent()
If this is what you're after, you could also have a look at What uses are there for "placement new"?