1

Possible Duplicate:
When to use virtual destructors?

Possible Duplicate of When to use virtual destructors?

I was wondering if someone could help me understand the need of virtual destructors.

I have written an application with a main dialog, and from this main dialog other derived dialogs will be spawned.

Therefore, would all of these derived dialogs require a virtual destructor? or just the main dialog?

Thank you in advance

Community
  • 1
  • 1
Irrelevant
  • 61
  • 6
  • You may want to read [this blog post](http://blogs.msdn.com/b/oldnewthing/archive/2004/05/07/127826.aspx). – Mr.C64 Feb 01 '13 at 10:50

4 Answers4

2

In general, if a class is designed to be used as a base class, it should have a virtual destructor. The only exceptions are convenience classes which provide things like typedef (see for example std::exception). The safest solution for these would be to make the destructor protected, but in fact, their semantics are such that no one ever creates a pointer to them anyway, so the problem doesn't occur in practice.

James Kanze
  • 142,482
  • 15
  • 169
  • 310
1

Virtual destructors are needed when you are going to be using these objects polymorphically. It's enough for the base class destructor to be virtual; the derived destructors will be implicitly virtual as well.

In your case it doesn't look like you will be using the dialogs polymorphically, so perhaps you don't need a virtual destructor at all.

Jon
  • 396,160
  • 71
  • 697
  • 768
-1

If you want all the destructors to be called in a chain you must ALWAYS create a virtual destructor. Even if one is empty.

It you miss to create a virtual destructor at some point C++ will create one non-virtual and thus will break all the destructors chain.

For non-virtual destructors they will be called on the class pointer of which you delete explicitly. If you use virtual - all the chain will be always called.

strannik
  • 1,317
  • 1
  • 12
  • 19
-1

The simple rule is "You need a virtual destructor as soon as you have virtual functions in the class."

And once you make a function in a baseclass virtual, it will become virtual for all derived classes, whether you mark it as such or not. So if you make the main dialog destructor virtual, you've done the job for all others [although I find it useful to see immediately that a function is virtual when looking at the class declaration, and not have to traipse several layers of classes up to figure out if it is or isn't].

Mats Petersson
  • 119,687
  • 13
  • 121
  • 204