2

What is the application of virtual and pure virtual destructor in C++? What is the scenario where I would have to use a virtual destructor instead of a normal destructor?

Arun Suryan
  • 1,615
  • 1
  • 9
  • 27
  • 2
    If you have a polymorphic inheritance hierarchy you're more or less required to use virtual destructors, or chaos can ensue when the correct constructors are not called. Just about any decent text book or tutorial or class should have brought this up. – Some programmer dude Mar 26 '20 at 06:26
  • 1
    A possible duplicate of https://stackoverflow.com/questions/1219607/why-do-we-need-a-pure-virtual-destructor-in-c and https://stackoverflow.com/questions/461203/when-to-use-virtual-destructors – tangoal Mar 26 '20 at 08:00

1 Answers1

0

When a pointer to a base class object is deleted, the compiler calls the corresponding destructor based on the actual type of object the pointer refers to.

If the base class destructor is not a virtual function, the compiler will automatically call the destructor of the base class when the base class pointer to the derived class object is deleted, without considering whether the actual object is an object of the base class.This can lead to memory leaks.

lizb_6626
  • 71
  • 5