Base
is the base class and Derived
is the derived class.
Base* p = new Derived;
delete p;
Let's assume that the base destructor is not virtual. Does this cause memory leak, if yes, why? And what would be the solution to fix it?
Base
is the base class and Derived
is the derived class.
Base* p = new Derived;
delete p;
Let's assume that the base destructor is not virtual. Does this cause memory leak, if yes, why? And what would be the solution to fix it?
It might.
It might not.
It might explode your computer.
It has undefined behaviour.
Stop asking about it and simply don't do it. :)
"Let's assume that the base destructor is not virtual. Does this cause memory leak, "
Easily, yes. If Derived
holds some dynamically allocated memory that should be deleted with it's destructor.
"if yes, why?"
See explanation above. Derived
's destructor won't be called.
"And what would be the solution to fix it?"
Make the Base
class destructor virtual
.
Let suppose that both classes has trivial destructor but Derived class has member with non trivial destructor that Base has not. (std::vector for example) that would leak memory, because destructor of vector will not be called.
If there's no dynamic member data in the Base
class, it won't cause a memory leak. Still reeks of smell. A code smell.