2

What is the usage of writing a virtual destructor in C++, like this:

class CMyObject
{
   CMyObject(void) {};
   virtual ~CMyObject(void) {};
}
Mormegil
  • 7,955
  • 4
  • 42
  • 77
alancc
  • 487
  • 2
  • 24
  • 68
  • possible duplicate of [When to use virtual destructors?](http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors) – songyuanyao Mar 21 '14 at 09:51

3 Answers3

1

So that you can have an array of CMyObject subclasses' objects of different size destroyed (and deallocated) properly.

Alex Watson
  • 519
  • 3
  • 13
1

The virtual destructor allows a subclass of CMyObject to override ~CMyObject(void) and properly clean up any additional properties that it owns.

For example, if you extend CMyObject to own a pointer to some array, and you allocate memory for that array, you must clean it up in the destructor of the subclass, because it will not be taken care of by the destructor of the superclass (CMyObject).

JuJoDi
  • 14,627
  • 23
  • 80
  • 126
1

Simple example:

class Foo {};
class Bar : Foo {};

Foo * obj = new Bar();
delete obj;

In this situation, without virtual destructor in Foo, destructor of Bar will not be called, and this is serious problem.

Bogdan
  • 984
  • 8
  • 16
  • So if there are no derived class for CMyObject and I always make sure CMyObject *p and p = new CMyObject, then declare destructor as NON virtual is OK? – alancc Feb 14 '14 at 23:16
  • @user2704265 Yes, it's true. Rule of the thumb is to declare virtual dtor for interfaces. – Bogdan Feb 15 '14 at 08:30