Part 3: All About Virtual Keyword in C++: How Does Virtual Destructor Works?
Tags: cpp, programming, tutorial, computerscience
Published: 2020-05-27 13:41:45

<!-- wp:paragraph -->
<p>Finally, we are in the 3rd &amp; last part of this series. We have already discussed how <a rel="noreferrer noopener" aria-label="virtual function (opens in a new tab)" href="http://www.vishalchovatiya.com/part-1-all-about-virtual-keyword-in-cpp-how-virtual-function-works-internally/" target="_blank"><span style="color:#0833f0" class="color">virtual function</span></a> &amp; <a rel="noreferrer noopener" aria-label="virtual class (opens in a new tab)" href="http://www.vishalchovatiya.com/part-2-all-about-virtual-keyword-in-cpp-how-virtual-class-works-internally/" target="_blank"><span style="color:#041be7" class="color">virtual class/inheritance</span></a> works internally in previous parts. We left one topic i.e. "How Does Virtual Destructor Works?" which we will see now. As usual, before learning anything new I usually start with “Why Do We Need It in the First Place?”</p>
<!-- /wp:paragraph -->

> /!\\\: Originally published @ [www.vishalchovatiya.com](http://www.vishalchovatiya.com/).

<!-- wp:heading -->
<h2>Why Do We Need a Virtual Destructor?</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>We will understand this with our earlier example(slightly twisted):</li></ul>
<!-- /wp:list -->
```c++
class protocol_t {
    private:
        uint8_t *_type;
        // storage ...
    public:
        protocol_t() { _type = new uint8_t; }
        ~protocol_t() { cout<<"~protocol_t"; delete _type; }

        virtual void authenticate(){};
        virtual void connect(){};
        // operations ...
};

class wifi_t : public protocol_t {
    private:
        char *_pass;
        // storage ...
    public:
        wifi_t() { _pass = new char[15]; }
        ~wifi_t() { cout<<"~wifi_t"; delete _pass; }

        virtual void authenticate(){};
        virtual void connect(){};
        // operations ...
};

class bluetooth_t : public protocol_t {
    private:
        char *_pass;
        // storage ...
    public:
        bluetooth_t() { _pass = new char[15]; }
        ~bluetooth_t(){ cout<<"~bluetooth_t"; delete _pass; }

        virtual void authenticate(){};
        virtual void connect(){};
        // operations ...
};

void makeConnection(protocol_t *protocol) {
    protocol->authenticate();
    protocol->connect();
    // Do some tx & rx
    delete protocol;
}    

int main() {
    int prot_type = rand() % 2; 
    makeConnection( (prot_type) ? new wifi_t : new bluetooth_t);
    return 0;
}
```

<!-- wp:list -->
<ul><li>So, we have created <code>wifi_t</code> &amp; <code>bluetooth_t</code> objects dynamically in <code>main()</code> and passed it to function <code>makeConnection()</code>.</li><li>An objects of <code>wifi_t</code>, <code>bluetooth_t</code> &amp; <code>protocol_t</code> also uses heap memory at construction &amp; destruction time.</li><li>Well, this code compiles &amp; runs fine without any error. But when you run above code, at the time of <code>delete protocol</code> line it always calls the destructor of <code>protocol_t</code> which you can verify by <code>~protocol_t</code> print on console.</li><li>We are freeing only sub-object resources which is <code>protocol_t</code> in call of <code>~protocol_t()</code> destructor. This means that there is a memory leak as we are not freeing heap memory resource of an object pointed by the pointer <code>protocol_t</code> in function <code>makeConnection()</code>.</li><li>We even don't know the type of object <code>protocol_t</code> pointer pointed to at the run time.</li><li>Virtual destructors are there to solve this problem. What we have to do is that</li></ul>
<!-- /wp:list -->

```c++
//...
virtual ~protocol_t() { cout<<"~protocol_t"; delete _type; }
//...
```

<!-- wp:list -->
<ul><li>Put keyword <strong>virtual</strong> in front of destructor <code>~protocol_t()</code>. Now <code>delete protocol</code> line will not directly call the destructor of <code>protocol</code>, rather it calls destructor indirectly i.e. using virtual table mechanism(in other words, dynamic dispatch).</li><li>This way it calls the destructor of the object pointed i.e. either <code>~wifi_t()</code> or <code>~bluetooth_t()</code> by pointer <code>protocol</code> &amp; then call the destructor of its base class i.e. <code>~protocol_t()</code>.</li><li>Hence, <strong><em>virtual destructor uses to delete the object pointed by base class pointer/reference</em></strong>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>How Does Virtual Destructor Works?</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>The question is how our destructor of a derived class called. The answer is simple it calls the destructor indirectly i.e. using virtual table pointer(<code>_vptr</code>). Let's understand it with the assumption that our pointer <code>protocol</code> points to an object of type <code>wifi_t</code>.</li></ul>
<!-- /wp:list -->

```c++
protocol_t *protocol = new wifi_t;
delete protocol;
```

<!-- wp:list -->
<ul><li>Here is the memory layout of the object <code>wifi_t</code></li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"linenumbers":"false"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">|                                |          
|--------------------------------| &lt;------ wifi_t class object memory layout
|  protocol_t::_type             |          
|--------------------------------|          
|  protocol_t::_vptr_protocol_t  |----------|
|--------------------------------|          |----------|-------------------------|
|  wifi_t::_pass                 |                     |   type_info wifi_t      |
|--------------------------------|                     |-------------------------|
|                                |                     |   wifi_t::authenticate  |
|                                |                     |-------------------------|
|                                |                     |   wifi_t::connect       |
|                                |                     |-------------------------|
|                                |                     |   wifi_t::~wifi_t       |
|                                |                     |-------------------------|</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>Now, the statement <code>delete protocol;</code> will probably be transformed by a compiler into</li></ul>
<!-- /wp:list -->

```c++
//...
(*protocol->vptr[3])(protocol);  // Equivalent to `delete protocol;`
//...
```

<!-- wp:list -->
<ul><li>Till here it was simple for us to understand how things are working. Because this is similar to a <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/part-1-all-about-virtual-keyword-in-cpp-how-virtual-function-works-internally/" target="_blank"><span style="color:#281fe1" class="color">virtual function</span></a> mechanism which we have seen in earlier articles. But the real magic comes when the destructor of a base class i.e. <code>protocol_t</code> will be called.</li><li>Which is again done with augmented code by the compiler in derived class destructor &amp; probably be:</li></ul>
<!-- /wp:list -->

```c++
~wifi_t() { 
    cout<<"~wifi_t"; 
    delete this->_pass;

    // Compiler augmented code ----------------------------------------------------
    // Rewire virtual table
    this->vptr = vtable_protocol_t; // vtable_protocol_t = address of static virtual table

    // Call to base class destructor
    protocol_t::~protocol_t(this); 
    // ----------------------------------------------------------------------------
}
```

<!-- wp:list -->
<ul><li>The process of destructing an object takes more operations than those you write inside the body of the destructor. When the compiler generates the code for the destructor, it adds extra code both before and after the user-defined code. Here we have only taken after code for the sake of understanding.</li><li>The same process will happen no matter how long tree up there is.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Verifying Compiler Augmented Code in Case of the Virtual Destructor</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Although you can not see compiler augmented code(unless if you disassemble it), we can use one hack that will prove that compiler insert the call of base class destructor in a derived class destructor when we use a virtual destructor. </li><li>For the same, consider the following code:</li></ul>
<!-- /wp:list -->

```c++
class base {
  public:
    virtual ~base()=0;
};

class derived : public base{
  public:
    ~derived(){}
};

int main(){
  base *pbase = new derived;
  delete pbase;
  return 0;
}
```

<!-- wp:list -->
<ul><li>When we use <strong><em>pure virtual destructor</em></strong>, the compiler will throw the following error at the time of linking:</li></ul>
<!-- /wp:list -->

```c++
exit status 1
/tmp/main-06bc44.o: In function `derived::~derived()':
main.cpp:(.text._ZN7derivedD2Ev[_ZN7derivedD2Ev]+0x11): undefined reference to `base::~base()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```

<!-- wp:list -->
<ul><li>Hence, compiler tried to add the code for base class destructor call in the derived class destructor. But due to unavailability of base class destructor definition linker exited with an error.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Tricky Example: Guess the Output</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Following example stolen from <a href="https://stackoverflow.com/questions/7750280/how-does-virtual-destructor-work-in-c" target="_blank" rel="noreferrer noopener">stackoverflow</a>:</li></ul>
<!-- /wp:list -->

```c++
struct base {
   virtual ~base() { f(); }
   virtual void f() { std::cout << "base"; }
};
struct derived : base {
   void f() { std::cout << "derived"; }
};
int main() {
   base * p = new derived;
   delete p;
}
```

<!-- wp:list -->
<ul><li>I would recommend you to guess the output first &amp; run it. If you get goosebump, try to interpret below line.</li><li>Standard mandates that the runtime type of the object is that of the class being constructed/destructed at this time, even if the original object that is being constructed/destructed is of a derived type. </li><li>Hence, it prints the output <code>base</code>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Summary</h2>
<!-- /wp:heading -->

<!-- wp:list {"ordered":true} -->
<ol><li>Virtual destructor uses to delete the object pointed by base class pointer/reference</li><li>Call to virtual destructor is done using dynamic dispatch</li><li>Compiler augments the derived class destructor code by inserting a call to the base class destructor</li><li>The runtime type of the object is that of the class being constructed/destructed at this time, even if the original object that is being constructed/destructed is of a derived type</li></ol>
<!-- /wp:list -->

[Have Any Suggestions, Query or Wants to Say `Hi`? Take the Pressure Off, You Are Just a Click Away.](http://www.vishalchovatiya.com/contact-2/)🖱️