C++ - what is a virtual destructor

A base class destructor must be declared virtual, in order for the derived class destructor to be called when the object is deleted through a base class pointer.

Stroustrup recommends declaring a destructor virtual whenever the (base) class has at least one virtual function.

"Having virtual functions indicate that a class is meant to act as an interface to derived classes, and when it is, an object of a derived class may be destroyed through a pointer to the base."

A virtual destructor example:

  // deleting through a base class pointer
  int main()
      CDog* pDog = new CDomesticDog();
      delete pDog;
      return 0;

  // base class CDog
  class CDog {
      virtual ~CDog() { // virtual destructor (must be declared virtual in base class).

  // derived class CDomesticDog
  class CDomesticDog : public CDog {
      char* m_pData;
      CDomesticDog() {
          m_pData = new char[128] { };
      ~CDomesticDog() override { // derived class destructor will be called. resources will be freed. override is optional but recommended.
          delete m_pData;

Ads by Google

Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath