Search

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. The base object is shared between all objects in the inheritance tree and it is only constructed once. 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 object, you will get only one copy of PoweredDevice per Copier 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, all classes inheriting a virtual base class will have a virtual table, even if they would normally not have one otherwise, and thus be larger by a pointer.

Because Scanner and Printer derive virtually from PoweredDevice, Copier will only be one PoweredDevice subobject. Scanner and Printer both need to know how to find that single PoweredDevice subobject, so they can access its members (because after all, they are derived from it). This is typically done through some virtual table magic (which essentially stores the offset from each subclass to the PoweredDevice subobject).

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

86 comments to 12.7 — Virtual base classes

  • Cakes

    Hey!

    For completion's sake, maybe add that instantiating multiple Copier objects will construct a PoweredDevice per Copier, took me a couple minutes to grasp that it's merely overriding all it's derived base class's(scanner and printer's) virtual constructor calls and calling it itself.

    Making more than one Copier illustrates a separate base class call. For me, the line that caused my confusion was: "This creates what is called a virtual base class, which means there is only one base object that is shared" , which led me to think it was some sort of static base.

    Just a suggestion, do with it as you like,

    Cheers,
    Cakes

  • Susano

    Hi Alex,
    How about situation which create Printer class and Scanner class share the same PowerDevice object?  In this case there is no Copier class, is it still possible?

    //Btw, this lesson is 12.7 but page url is 128 (https://www.learncpp.com/cpp-tutorial/128-virtual-base-classes/)

    • nascardriver

      Hi Susano!

      When you create a `Printer` or `Scanner` separately, they'll each have their own `PoweredDevice`.

      > this lesson is 12.7 but page url is 128
      Thanks for pointing it out. The urls aren't updated so that links to the lesson continue to work. When a lesson's title is changed, the url stays the same.

  • Hadi

    Hello Alex

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

    isn't ...a Copier object instead of Copier class ??

  • Nirbhay

    In the following code, I do not understand the comment:
    "// this line is required to create Scanner objects, but ignored in this case" on line 16 and same for line 26.

    Why is it not ignored in the previous example (without virtual base class)?

    Code:

    Thanks!

    • In the previous example there's one `PoweredDevice` as the base of `Printer` and one as the base of `Scanner`.
      When they inherit virtually, there's only one `PoweredDevice` for both. This `PoweredDevice` gets constructed by `Copier`, so the calls in `Scanner` and `Printer` have no effect.

      • Nirbhay

        Ok, so
        instead "// this line is required to create Printer objects, but ignored in this case"

        it should be
        "// this line is required to create 'PoweredDevice' objects, but ignored in this case" , right?

        • Kind of. The `PoweredDevice` is constructed as a part of the `Printer` or `Scanner`. The line is used when you construct a `Printer` or `Scanner`. It's unused when the `Printer` or `Scanner` is created during construction of a `Copier`.

  • this code show some error in dev c++

  • Atas

    Typo:
    Because Scanner and Printer derive virtually from PoweredDevice, Copier will only >>>be<<< one PoweredDevice subobject.

  • Anthony

    I think we can say this?:

    Classes themselves can inherit virtually, which means that construction of the base subobject is effectively kicked down the road to the most derived class. Within the definition of a class that inherits virtually from a base class, any calls to the constructor of the virtual base class will simply be ignored. For example, this addresses the 'diamond problem': (etc..)

    • Anthony

    • Anthony

      I'd edit what I wrote slightly:
      "Classes themselves can inherit virtually, which means that construction of the base subobject is effectively kicked down the road to the most derived class. Within the definition of a class that inherits virtually from a base class, any calls to the constructor of the virtual base class will simply be ignored (but must be present!). For example, this addresses the 'diamond problem': (etc..)"

  • Anthony

    "if Copier was singly inherited from Printer, and Printer was virtually inherited from PoweredDevice,"

    Perhaps "if Copier singly inherits from Printer, and Printer virtually inherits from PoweredDevice," is a little clearer?

    I know, it's a trifle

  • the above code doesn't work with TurboC++ what i have to do for this problem please suggest me

  • Prashanth CM

    I tried writing whole program by only having default constructor( No parameters). In that case, PoweredDevice constructor call from Copier constructor was not included and it was giving expected results. How is that possible?

  • Spixmaster

    I think that the url is wrong.

    .../cpp-tutorial/128-virtual-base-classes/

    Should not it be 127?

  • "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." , the virtual base is considered a direct base of most derived class, so why the virtual table is set for each class deriving from the virtual base pointing to the most derived, i thought that the connection between the virtual base and its derived are lost so how a virtual table between in these derived pointing to the most derived would help ?

  • Hi Alex!

    The call to the @PoweredDevice constructor should be moved before the ones to @Scanner and @Printer.

    Your order produces warnings
    warning: base class 'Printer' will be initialized after base 'PoweredDevice' [-Wreorder]
    warning: base class 'Scanner' will be initialized after base 'PoweredDevice' [-Wreorder]

  • Viktar

    Hi Alex, there's one thing I don't understand.

    In constructors in derived class where we need to instantiate Base class there is some difference in initialization.

    For example, if you try to initialize Scanner, Printer and PoweredDevice in Copier in uniform manner (Like Scanner{scanner, power}, Printer{printer, scanner}, etc.) the behaviour is not the same as Scanner(scanner, power), Printer(printer, power), etc.

    I checked chapter "2.1 — Fundamental variable definition, initialization, and assignment" where it says Rule: If you’re using a C++11 compatible compiler, favor uniform initialization

    And additional I checked 8.5 "Constructors" and where it says Rule: Use direct or uniform initialization with your classes.
    + "8.5a — Constructor member initializer lists" the same Rule: Favor uniform initialization over direct initialization if your compiler is C++11 compatible. Actually I didn't find any strings where you're using uniform initialization for to instantiate base class.

    + 11.4 — Constructors and initialization of derived classes - as I see you haven't mentioned uniform initialization at all.

    Could you describe this difference a little bit clearly. Thank you.

    P.S. I use CodeBlocks 17.2 on Debian 9.

    • Hi Viktar!

      I'm unable to reproduce what you described. Both

      and

      (should) produce the same results. Did you do anything other than that? If so, what? If no, which compiler are you using? Make sure you're running it's newest version.

      > Actually I didn't find any strings where you're using uniform initialization
      Alex doesn't use uniform initialization himself, because he's old :). You should do so.

      • Viktar

        If I use this code

        then result is expected.

        In the same time when I use this code

        I've got next result :

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

        The compiler version is: gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516

        Looks like gcc is quite old

        • It looks like @PoweredDevice is getting called from all three @Printer, @Scanner and @Copier, which should not be happening, because only the call to @PoweredDevice from @Copier has an effect on the resulting object. It could be that the standard allows the behavior you're experiencing, nonetheless I suggest you to update g++ to get consistent results. g++ 8.2.1 produces the same output no matter which initialization is used.

        • Jack

          Hi, did you resolve this? I have the same problem, code::blocks 17.12, C++17 compiler flag set, windows 10.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]