alancc
alancc

Reputation: 811

What is the usage of virtual destructor?

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

class CMyObject
{
   CMyObject(void) {};
   virtual ~CMyObject(void) {};
}

Upvotes: 2

Views: 78

Answers (3)

Bogdan
Bogdan

Reputation: 986

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.

Upvotes: 1

JuJoDi
JuJoDi

Reputation: 14975

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).

Upvotes: 1

Alex Watson
Alex Watson

Reputation: 519

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

Upvotes: 1

Related Questions