RAD Studio
ContentsIndex
PreviousUpNext
Virtual Destructors

A destructor can be declared as virtual. This allows a pointer to a base class object to call the correct destructor in the event that the pointer actually refers to a derived class object. The destructor of a class derived from a class with a virtual destructor is itself virtual.

/* How virtual affects the order of destructor calls.
   Without a virtual destructor in the base class, the derived
   class destructor won't be called. */
#include <iostream>
class color {
public:
   virtual ~color() {  // Virtual destructor
      std::cout << "color dtor\n";
      }
};
class red : public color {
public:
   ~red() {  // This destructor is also virtual
      std::cout << "red dtor\n";
      }
};
class brightred : public red {
public:
   ~brightred() {  // This destructor is also virtual
       std::cout << "brightred dtor\n";
       }
};
int main()
{
   color *palette[3];
   palette[0] = new red;
   palette[1] = new brightred;
   palette[2] = new color;
   // The destructors for red and color are called.
   delete palette[0];
   std::cout << std::endl;
   // The destructors for bright red, red, and color are called.
   delete palette[1];
   std::cout << std::endl;
   // The destructor for color is called.
   delete palette[2];
   return 0;
}

Program Output:

red dtor
color dtor
brightred dtor
red dtor
color dtor
color dtor

However, if no destructors are declared as virtual, delete palette[0], delete palette[1], and delete palette[2] would all call only the destructor for class color. This would incorrectly destruct the first two elements, which were actually of type red and brightred.

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!