0

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?

Southee
  • 69
  • 3

4 Answers4

2

It might.

It might not.

It might explode your computer.

It has undefined behaviour.

Stop asking about it and simply don't do it. :)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

"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.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

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.

Luka Rahne
  • 10,336
  • 3
  • 34
  • 56
0

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.

Don Larynx
  • 685
  • 5
  • 15