12.7 — Virtual base classes

Last chapter, in lesson 11.7 -- Multiple inheritance, we left off talking about the “diamond problem”. In this section, we will resume this discussion.

Note: This section is an advanced topic and can be skipped or skimmed if desired.

The diamond problem

Here is our example from the previous lesson (with some constructors) illustrating the diamond problem:

Although you might expect to get an inheritance diagram that looks like this:

If you were to create a Copier class object, by default you would end up with two copies of the PoweredDevice class -- one from Printer, and one from Scanner. This has the following structure:

We can create a short example that will show this in action:

This produces the result:

PoweredDevice: 3
Scanner: 1
PoweredDevice: 3
Printer: 2

As you can see, PoweredDevice got constructed twice.

While this is often desired, other times you may want only one copy of PoweredDevice to be shared by both Scanner and Printer.

Virtual base classes

To share a base class, simply insert the “virtual” keyword in the inheritance list of the derived class. This creates what is called a virtual base class, which means there is only one base object that is shared. Here is an example (without constructors for simplicity) showing how to use the virtual keyword to create a shared base class:

Now, when you create a Copier class, you will get only one copy of PoweredDevice that will be shared by both Scanner and Printer.

However, this leads to one more problem: if Scanner and Printer share a PoweredDevice base class, who is responsible for creating it? The answer, as it turns out, is Copier. The Copier constructor is responsible for creating PoweredDevice. Consequently, this is one time when Copier is allowed to call a non-immediate-parent constructor directly:

This time, our previous example:

produces the result:

PoweredDevice: 3
Scanner: 1
Printer: 2

As you can see, PoweredDevice only gets constructed once.

There are a few details that we would be remiss if we did not mention.

First, virtual base classes are always created before non-virtual base classes, which ensures all bases get created before their derived classes.

Second, note that the Scanner and Printer constructors still have calls to the PoweredDevice constructor. When creating an instance of Copier, these constructor calls are simply ignored because Copier is responsible for creating the PoweredDevice, not Scanner or Printer. However, if we were to create an instance of Scanner or Printer, those constructor calls would be used, and normal inheritance rules apply.

Third, if a class inherits one or more classes that have virtual parents, the most derived class is responsible for constructing the virtual base class. In this case, Copier inherits Printer and Scanner, both of which have a PoweredDevice virtual base class. Copier, the most derived class, is responsible for creation of PoweredDevice. Note that this is true even in a single inheritance case: if Copier was singly inherited from Printer, and Printer was virtually inherited from PoweredDevice, Copier is still responsible for creating PoweredDevice.

Fourth, a virtual base class is always considered a direct base of its most derived class (which is why the most derived class is responsible for its construction). But classes inheriting the virtual base still need access to it. So in order to facilitate this, the compiler creates a virtual table for each class directly inheriting the virtual class (Printer and Scanner). These virtual tables point to the functions in the most derived class. Because the derived classes have a virtual table, that also means they are now larger by a pointer (to the virtual table).

12.8 -- Object slicing
12.6 -- Pure virtual functions, abstract base classes, and interface classes

38 comments to 12.7 — Virtual base classes

  • sandhya

    Hi Alex,

    I have read somewhere like “base class construtor,destructor,assignment operator and copy constuctors will not get inherited to derived class”. Why is it so? Can u explain me?

    • saini

      sandhya, constructor and destructor can not be inherited because a constructor have same name as its class and i don't think there are two classes existing in your program having same name….
      this is also true in case of destructor

  • Stuart

    You explained that very well, Alex. Wasn’t hard to understand at all.

  • sonika

    this is good explanation.Could you please tell me about an extra pointer is created when we do virtual inheritance.If i want to know size of copier class what it will be and how?

    • Alex

      The extra pointer comes about because the compiler has to set up a virtual table to make the classes that inherit from the virtual base work correctly. We talk about the virtual table in chapter 12.

  • Stefan

    Thanks for the tutorial. I understood everything but this part not:

    “First, virtual base classes are created before non-virtual base classes, which ensures all bases get created before their derived classes.”

    Why virtual bases are created before non-virtual bases?


    • Alex

      Simply put, creating the virtual base classes first ensures all virtual base classes get created before the non-virtual classes that may need them.

      In this case, it doesn’t really matter since neither Scanner nor Printer use anything from PoweredDevice. But if they did, you’d definitely want to ensure PoweredDevice had been initialized before Scanner or Printer.

  • This is great article. I should have read this before going to interviews 🙂

  • venkatesh


    how i will solve dimond problem in multiple inheritence with out using “VIRTUAL” keyword.
    please help me out…

  • RAVI

    Hi this is very good one

  • addy

    Great!! Excellent explanation. Last 3 points are very good, something i have not known earlier.

  • obba

    please can you explain other problems about inheritance?

  • saini

    HI ALEX,

    • Alex

      The short answer is: a virtual base class is always considered a direct base of its most derived class. Thus, even though it appears like PoweredDevice is a base class of Scanner and Printer, it’s actually a base of Copier, and the compiler does some interesting tricks to make Scanner and Printer work as expected.

      I’m not sure why this rule was picked (instead of making construction of the virtual base class the responsibility of the class doing this “joining”).

  • A. Syukri Abdollah

    The most derived class. How it is so misleading. One would’ve assumed it’s the class which is most derived from (which is, in this case, the base class). They should’ve named it deriving class, so that at least Alex’s tutorial would be easier to understand 🙂

  • Lokesh

    Hi friends,

    Explanation given is only helpful for basic user and for Desktop application.

    But in Embedded u require more information. for example how Compiler store this information that only 1 object will be initiated.
    like for virtual function we have virtual table concept

  • deepak.sisodiya

    thanks bady…..

  • bantoo011

    Please explain me the solution of diamond problem in terms of vtable & vptr .


  • Jeanne

    Very good article ! Thanks a ton !

  • Leo

    These are good tutorials

  • Frank

    What happens if one of the base classes, that is, printer or scanner is derived as virtual and the other is not. Now, if we create an instance of copier, which one is responsible to call the constructor of powereddevice?
    Great tutorials by the way.

    • Alex

      In the case you indicate, the compiler will error out because Copier isn’t allowed to call the constructor of PoweredDevice directly if it’s not virtual.

  • Octavian

    "multiple inheritance" link at the top of the page points to this page. It should point to previous section being 11.7.

  • Ryan B

    Thank you very much for the tutorials!

    I have a question on a very edge case (as protected/private inheritance is rare enough without also involving multiple inheritance):

    What happens if the two parent classes inherit the base differently (e.g. Scanner inherits privately rather than publicly)?

    • Ryan B

      My thoughts:
      Since the most derived class is responsible for constructing the base, it seems like the base is acting as a temporary (or virtual?) parent. In this case, then all three of the inherited classes could be considered equal base classes for Copier. Is this what you meant on your first point, when you say that virtual base classes are constructed before non-virtual base classes?

      If this is the case, then there is no way to specify inheritance from the virtual base. In this case, does it default to public (rather than private)?

      • Alex

        I wasn’t sure, so I had to do some experimentation. The most derived class can access the virtual base class so long as at least one of the derived classes provides an access path. So in the lesson example, if we made Scanner private, Copier could still access the members of PoweredDevice through Printer.

  • prats

    In case we don’t call the PoweredDevice’s constructor from list of Copier constructor while still declaring it as virtual, would it still work ?
    Would the Scanner and Printer class then create the PoweredDevice object?

    • Alex

      No. If PoweredDevice had a default constructor, that would get used. If it didn’t, you get an error about no appropriate constructor found for PoweredDevice.

  • Anddo

    2 questions

    1- If there is CopierTwo class which is derived from Copier class, which of them is responsible of constructing PoweredDevice ?

    In case Copier object created in the main function, then Copier can and responsible for constructing PoweredDevic ? I think this is logical but

    Similarly, in case CopierTwo object created in the main function, then CopierTwo can and responsible for constructing PoweredDevic & Copier ? or only Copier (and Copier constructs PoweredDevic?)

    2- When you said "First, virtual base classes are created before non-virtual base classes, which ensures all bases get created before their derived classes.", what do you mean in context of the last example mentioned.

    Do you mean PoweredDevice is constructed first then Printer and Scanner ?
    or Printer and Scanner first then PoweredDevice ?

    I’m confused on this number 2 question since the last example output is

    PoweredDevice: 3
    Scanner: 1
    Printer: 2

    which means PoweredDevice is constructed first in the "normal" chain construction of inheritance tree. Copier constructor hold > Printer constructor hold & Scanner constructor hold > PoweredDevice constructor execute > Printer constructor execute & Scanner constructor execute > Copier constructor execute.

    Maybe I’m getting it wrong and you actually talking about something else (like if there is third class on Printer & Scanner level but it inherits non-virtual PoweredDevice) So what you meant exactly by this please ?

    • Alex

      1) Both Copier and CopierTwo need to be responsible for constructing PoweredDevice.
      2) Copier is responsible for creating Printer, Scanner, and PoweredDevice. Because virtual base classes are always created first, PoweredDevice gets created before Printer and Scanner, just in case PoweredDevice initializes something that Printer or Scanner need.

      Edit: Answer updated after Anddo responded.

      • Anddo

        1) it seems if I created CopierTwo then I have to explicitly call the base class. Here is what I tried

        So I guess whenever there is virtual inheritance in the chain, I have to explicitly call the base class constructor from ANY/ALL derivatives, no matter how deep they are ?

        2) Got that 🙂

        Another additional question

        3) I tried to make class inherits 3 classes which are only 2 of them have virtual inheritance to base class and the third one has normal inheritance to base class. On XCode, this appears to create two objects of the base class, while on Visual studio I get the error (ambiguous access of ‘A’). Here is the code

        Output of XCode is
        A is called and val = 5
        C is called
        B is called
        A is called and val = 4
        D is called
        E is called
        Program ended with exit code: 0
        So is this a bug or certain limitation in VS compiler or something ? Any explanation would much appreciated.

        As always, thanks for answering and for your great tutorials 🙂

        • Alex

          1) Yes, it appears you are correct. I had thought only Copier needed to create PoweredDevice(), and that CopierTwo could rely on Copier to create the PoweredDevice(). But it appears C++ isn’t that smart (yet), so both Copier and all classes derived from Copier need to create the PoweredDevice class.

          C++ has this to say:

          In a non-delegating constructor, initialization proceeds in the following order:

          — First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.

          — Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

          So most-derived classes have special rules to make virtual base classing work.

          3) This is a very interesting question. I’m not sure what the C++ standard has to say about this behavior, or how to resolve it. It looks like XCode is making a (reasonable) assumption that because your most-derived class is trying to call the base class constructor directly, it must be trying to access the virtual base class (as calling the non-virtual base class constructor directly would be illegal). Visual Studio isn’t making this distinction.

          I do note that in Visual Studio you can resolve this ambiguity like this:

          Surprisingly, the following also compiles in visual studio 2015:

          Though it doesn’t do what you’d expect: virtual base class A is still initialized with value 5, even though it looks like we’re specifying D’s non-virtual version of A() to initialize (which would be illegal, as it is a non-immediate base class through this path).

          IMO, this is probably a bug in Visual Studio, and XCode is probably handling this more correctly.

  • Matt

    Typo. In the last sentence before the first code snippet showing the "virtual" keyword in action, you wrote:
    " Here is the an example…"

  • dazedbrain

    Hi Alex,

    Typo found again 030

    "Here is an example (without constructors for simplicity) showing how to use to virtual keyword to create a shared base class:"

    Did you mean "to use the virtual keyword"

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter