-2

Every C++ programmer knows that, virtual destructor is used to ensure the proper destruction order of objects in inheritance hierarchy.

Where else "Virtual Destructors" are used/can be used in realtime scenarios?

1 Answers1

5

Your assumption is incorrect; being virtual does not affect the order of destruction. That's always from most derived to base class. It does affect which destructors are actually called! If you don't declare the destructors virtual, the full chain of destructors starting with most derived destructor might never get called.

Without virtual destructors, the call chain will start with the most derived class of the static type of the pointer or reference. If your actual object is a more derived type than that, there will be undefined behavior as those destructors are skipped.

For example:

class A { ... }; // base class
class B: public A { ... }; // derived class
class C: public B { ... }; // further derived

A* ABCFactory() { return new C; }

A* a = ABCFactory();
delete a;            // undefined behavior as destructors C and B are skipped
Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
Mark Ransom
  • 271,357
  • 39
  • 345
  • 578