int main()
{
Base *p = new Derived;
delete p;
return 0;
}
I have some confusion, why deleting p here won\'t delete the derived object ? Is
If you are asking about the behavior in situation when base class has no virtual destructor, then your confusion is stemming for the fact hat you already have a number of pre-conceived misconceptions about the behavior of this delete
expression
"It will only be able to delete the base class part of the object"
"This will cause memory leaks"
None of this makes any sense. There's no memory leaks here, and there's nothing as deterministic as being able to "delete the base class part" of it.
If the base class has no virtual destructor the behavior of such code is simply undefined. There are quite a few different ways that undefined behavior can manifest itself, including but not limited to improper destructor call, improper operator delete
selection, heap corruption and, yes, "memory leaks", both direct and indirect. There are many different things that can get screwed up in this case. Not just some "memory leaks", as the popular misconception makes people believe. (Where does that popular bit about "memory leaks" come from. Does anyone know?)
So, you do need virtual destructor here. And the full list of reasons you need it can get quite long, if one decides to make a full effort to analyze it exhaustively. But in any case, this is an implementation detail. There's no specific explanation of what will really happen without tying it to a specific implementation.
As for the "conceptual" explanation... There's always the most obvious one: it is, of course, necessary to invoke the proper destructor in order to performs the proper destruction. Even if we simply limit out consideration to user-defined destruction steps (i.e. what the user explicitly wrote in their derived-class destructor), we still need destructor polymorphism to properly invoke that destructor.
However, there are also a number of other internal reasons. For example, in a typical implementation selection of the proper operator delete
for raw memory deallocation also piggybacks on the virtuality of the destructor (see here, for example)