Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Virtual destructors are useful when you can delete an instance of a derived class through a pointer to base class:</p> <pre><code>class Base { // some virtual methods }; class Derived : public Base { ~Derived() { // Do some important cleanup } }; </code></pre> <p>Here, you'll notice that I didn't declare Base's destructor to be <code>virtual</code>. Now, let's have a look at the following snippet:</p> <pre><code>Base *b = new Derived(); // use b delete b; // Here's the problem! </code></pre> <p>Since Base's destructor is not <code>virtual</code> and <code>b</code> is a <code>Base*</code> pointing to a <code>Derived</code> object, <code>delete b</code> has <a href="https://stackoverflow.com/q/2397984/20984">undefined behaviour</a>:</p> <blockquote> <p>[In <code>delete b</code>], if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and <strong>the static type shall have a virtual destructor or the behavior is undefined</strong>.</p> </blockquote> <p>In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak.</p> <p>To sum up, always make base classes' destructors <code>virtual</code> when they're meant to be manipulated polymorphically.</p> <p>If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call <code>delete</code> on a base class pointer.</p> <p>You can learn more about virtuality and virtual base class destructor in <a href="http://www.gotw.ca/publications/mill18.htm" rel="noreferrer">this article from Herb Sutter</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload