This is Undefined Behaviour, which may, indeed, lead to memory leak:
The C++ Standard, [expr.delete], paragraph 3 [ISO/IEC 14882-2014], states:
In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.
Since no destructor in neither Base
nor Derived
is user-defined, a default destructor is added by the compiler. Those destructors are not virtual
.
Since base
is a Base*
, delete base
calls the destructor of the base class, which is Undefined Behaviour. In concrete terms, it leads to memory leak when you work with resources; in your case, since your classes only contain POD, I'd say there is no leak.
In order to fix the memory leak, one should define a virtual destructor for classes meant to be inherited:
struct Base
{
virtual ~Base() {}
int myInt;
};
struct Derived : Base
{
int myIntDerived;
};
int main()
{
Base *base = new Derived;
Derived *derived = new Derived;
delete base; // OK
delete derived; // OK
}