Part 2: All About Virtual Keyword in C++: How Does Virtual Base Class Works Internally?
Tags: cpp, programming, tutorial, computerscience
Published: 2020-05-26 03:31:48

<!-- wp:paragraph -->
<p>In <a rel="noreferrer noopener" aria-label="PART 1 (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:#1409f5" class="color">PART 1</span></a> of "All About Virtual Keyword in C++" series, we have discussed "How Does Virtual Function Works Internally?". So, in this article, I will discuss "How Does Virtual Base Class Works Internally?". I am iterating the same thing which I have mentioned in the earlier article as well that implementation of a virtual mechanism is purely compiler dependent. So, there is no C++ standard is defined for such dynamic dispatch. Hence, here I am discussing the general approach.</p>
<!-- /wp:paragraph -->

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

<!-- wp:paragraph -->
<p>As usual, before learning anything new I usually start with “Why do we need it in the first place?”</p>
<!-- /wp:paragraph -->

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

<!-- wp:list -->
<ul><li>When we use inheritance, we basically extending a derived class with base class functionality. In other words, the base class object would be treated as <a rel="noreferrer noopener" aria-label="sub-object (opens in a new tab)" href="http://www.vishalchovatiya.com/memory-layout-of-cpp-object/" target="_blank"><span style="color:#0300a3" class="color">sub-object</span></a> in the derived class.</li><li>As a result, this would create a problem in multiple inheritances if base class sharing the same mutual class as <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/memory-layout-of-cpp-object/" target="_blank">sub-object</a> in the top-level hierarchy and you want to access its property. </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Problem</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>I know above statement is a bit complex. So, let see an example.</li></ul>
<!-- /wp:list -->

```c++
class Top { public: int t; };
class Left : public Top { public: int l; };
class Right : public Top { public: int r; };
class Bottom : public Left, public Right { public: int b; };
```

<!-- wp:list -->
<ul><li>The above class hierarchy/inheritance results in the "diamond" which looks like below:</li></ul>
<!-- /wp:list -->

```c++
    Top
   /   \
Left   Right
   \   /
   Bottom
```

<!-- wp:list -->
<ul><li>An instance of <code>Bottom</code> will be made up of <code>Left</code>, which includes <code>Top</code>, and <code>Right</code> which also includes <code>Top</code>. So, we have two sub-object of <code>Top</code>. This will create ambiguity as follows:</li></ul>
<!-- /wp:list -->

```c++
Bottom *bot = new Bottom;
bot->t = 5; // is this Left's `t` or Right's `t` data member ??
```

<!-- wp:list -->
<ul><li>This was by far the simplest reason for the need of the virtual base class. And consider the following scenarios as an example:</li></ul>
<!-- /wp:list -->

```c++
Top   *t_ptr1 = new Left;
Top   *t_ptr2 = new Right; 
```

<!-- wp:list -->
<ul><li>These both will work fine as <code>Left</code> or <code>Right</code> object memory layout has <code>Top</code> subobject. You can see the memory layout of the <code>Bottom</code> object below for clear understanding.</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;------ Bottom bot;   // Bottom object 
|    Left::Top::t      |
|----------------------|
|    Left::l           |
|----------------------|
|    Right::Top::t     |
|----------------------|
|    Right::r          |
|----------------------|
|    Bottom::b         |
|----------------------|
|                      |</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>Now, what happens when we upcast a <code>Bottom</code> pointer?</li></ul>
<!-- /wp:list -->

```c++
Left  *left = new Bottom;
```

<!-- wp:list -->
<ul><li>This will work fine as <code>Bottom</code> object memory layout starts with <code>Left</code> subobject.</li><li> However, what happens when we upcast to <code>Right</code>?</li></ul>
<!-- /wp:list -->

```c++
Right  *right = new Bottom;
```

<!-- wp:list -->
<ul><li>For this to work, we have to adjust the <code>right</code> pointer value to make it point to the corresponding section of the <code>Bottom</code> layout:</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="">|                      |
|----------------------|
|    Left::Top::t      |
|----------------------|
|    Left::l           |
|----------------------|  &lt;------ right;
|    Right::Top::t     |
|----------------------|
|    Right::r          |
|----------------------|
|    Bottom::b         |
|----------------------|
|                      |
|                      |</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>After this adjustment, we can access the <code>Bottom</code> through the <code>right</code> pointer as a normal <code>Right</code> object.</li><li>But, what would happen if we do</li></ul>
<!-- /wp:list -->

```c++
Top* Top = new Bottom;
```

<!-- wp:list -->
<ul><li>This statement is ambiguous: the compiler will complain</li></ul>
<!-- /wp:list -->

```c++
error: `Top' is an ambiguous base of `Bottom'
```

<!-- wp:list -->
<ul><li>Although you can use force <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/cpp-type-casting-with-example-for-c-developers/" target="_blank"><span style="color:#1017d2" class="color">typecasting/C-style-cast</span></a> as follows:</li></ul>
<!-- /wp:list -->
```c++
Top* topL = (Left*) Bottom;
Top* topR = (Right*) Bottom;
```

<!-- wp:heading {"level":3} -->
<h3>Solution</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong><em>Virtual inheritance uses to solve such kind of diamond problems</em></strong>. When you specify virtual while inheriting your classes, you're telling the compiler that you only want a single instance.</li></ul>
<!-- /wp:list -->

```c++
class Top { public: int t; };
class Left : virtual public Top { public: int l; };
class Right : virtual public Top { public: int r; };
class Bottom : public Left, public Right { public: int b; };
```

<!-- wp:list -->
<ul><li>This means that there is only one "instance" of <code>Top</code> included in the hierarchy. Hence</li></ul>
<!-- /wp:list -->

```c++
Bottom *bot = new Bottom;
bot->t = 5; // no longer ambiguous
```

<!-- wp:list -->
<ul><li>So, this may seem more obvious and simpler from a programmer's point of view. But from the compiler's point of view, this is vastly more complicated. </li><li>But an interesting question is how this <code>bot-&gt;t</code> will be addressed &amp; handle by the compiler? Ok, this is the time to move on to next point.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>How Does Virtual Base Class Addressing Works Internally?</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>A class containing one or more virtual base class as a subobject, such as <code>Bottom</code>, is divided into two regions: <ol><li><strong><em>Invariant region</em></strong></li><li><strong><em>Shared region</em></strong></li></ol></li><li>Data within the invariant region remains at a fixed offset(which decided in compilation step) from the start of the object regardless of subsequent derivations. So members within the invariant region can access directly. In our case, its <code>Left</code> &amp; <code>Right</code> &amp; <code>Bottom</code>.</li><li>Additionally, the shared region represents the virtual base class subobjects whose location within the shared region fluctuates with an order of derivation &amp; subsequent derivation. So members within the shared region need to accessed indirectly.</li><li>As the name suggests, an <strong><em>invariant region placed at the start</em></strong> of objects memory layout and the <strong><em>shared region placed at the end</em></strong>. </li><li>The <strong><em>offset of the shared region updated in the virtual table</em></strong>.  The code necessary for this augmented by the compiler at the time of object construction. See below image for reference.</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;------ Bottom bot;   // Bottom object           
|    Left::l             |          
|------------------------|               |------------------| 
|    Left::_vptr_Left    |-------|       |  offset of Top   | // offset starts 
|------------------------|       |-------|------------------|       // from left subobject = 20
|    Right::r            |               |    ...           |
|------------------------|               |------------------|  
|    Right::_vptr_Right  |-------|       
|------------------------|       |       |------------------| 
|    Bottom::b           |       |       |  offset of Top   | // offset starts 
|------------------------|       |-------|------------------|       // from right subobject = 12                       
|    Top::t              |               |    ...           |                                    
|------------------------|               |------------------|                                            
|                        |       </pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>Now coming back to our interesting question i.e. "How this <code>bot-&gt;t</code> will be addressed?"</li></ul>
<!-- /wp:list -->

```c++
Bottom *bot = new Bottom;
bot->t = 5;
```

<!-- wp:list -->
<ul><li>Above code will probably be transformed into</li></ul>
<!-- /wp:list -->

```c++
Bottom *bot = new Bottom;
(bot + _vptr_Left[-1])->t = 5; // If you haven't got this, then consider the above memory map
```

<!-- wp:list -->
<ul><li>So, as you can see addressing of <a rel="noreferrer noopener" href="http://www.avabodh.com/cxxin/virtualbase.html" target="_blank">virtual base class</a> is done through the offset(of the base class) stored in the virtual table.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Handling of Virtual Functions in the Virtual Base Class</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Handling of the virtual functions in the virtual base class is the same as we have discussed in our previous <a rel="noreferrer noopener" aria-label="article (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:#0a19ee" class="color">article</span></a> with multiple inheritances. There is nothing special about it.</li></ul>
<!-- /wp:list -->

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

<!-- wp:paragraph -->
<p>As I mentioned earlier this seems straight forward from the programmer's point of view. But from the compiler’s point of view, it is complicated. And, there are many other <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/complications-of-using-the-virtual-base-class/" target="_blank"><span style="color:#0a19ee" class="color">Complications of Using the Virtual Base Class</span></a> which I have discussed in a separate article. Let's summaries few take away points:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>There is no C++ standard on dynamic dispatch implementation &amp; it only states behaviour</li><li>The virtual class needed to avoid the diamond problem</li><li>The object having virtual base class as subobject has memory layout divided in two regions:<ol><li>Invariant region: non-virtual classes</li><li>Shared region: virtual classes</li></ol></li><li>Shared region i.e. virtual base class subobject placed at the end of memory layout.</li><li>The addresses of the data members in the virtual base class resolved using offset(of virtual base class) store in the virtual table.</li></ul>
<!-- /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/)🖱️