[Solved] why do we need a virtual destructor with dynamic memory? [duplicate]


Imagine you have this:

class A { 
  public:
  int* x;     
}
class B : public A {
  public:
  int *y;
}


main() {
  A *var = new B;
  delete var;
}

Please assume some constructors destructors.
In this case when you delete A. If you have virtual destructors then the B destructor will be called first to free y, then A’s to free x.

If it’s not virtual it will just call A’s destructor leaking y.

The issue is that the compiler can’t know beforehand which destructor it should call. Imagine you have a if above that constructs A or B depending on some input and assings it to var.
By making it virtual you make the compiler deffer the actual call until runtime. At runtime it will know which is the right destructor based on the vtable.

4

solved why do we need a virtual destructor with dynamic memory? [duplicate]