Alex Rivera | Logout

Why should I declare a virtual destructor for an abstract class in C++?

Asked 2008-11-07T00:55:30.390
183

I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare virtual destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.

Edit
Report

1 Answer

36

The answer to your question is often, but not always. If your abstract class forbids clients to call delete on a pointer to it (or if it says so in its documentation), you are free to not declare a virtual destructor.

You can forbid clients to call delete on a pointer to it by making its destructor protected. Working like this, it is perfectly safe and reasonable to omit a virtual destructor.

You will eventually end up with no virtual method table, and end up signalling your clients your intention on making it non-deleteable through a pointer to it, so you have indeed reason not to declare it virtual in those cases.

[See item 4 in this article: http://www.gotw.ca/publications/mill18.htm]

answered 2008-11-07T02:39:47.980

Your Answer