You are here:

C++/What is virtual inheritance?

Advertisement


Question
Hi,

What is virtual inheritance?

Thanks,
lzzzz

Answer
This is something you find may be required if you are using multiple inheritance. In that case it is possible for a class to be derived from other classes which have the same base class. In such cases, without virtual inheritance, your objects will contain more than one sub-object of the base type the base classes share. Whether this is what is the required effect depends on the circumstances. If it is not then you can use virtual inheritance by specifying virtual base classes for those base types for which a whole object should only contain one such base class sub-object.

Taking examples from "The C++ Programming Language" (3rd or special editions) by Bjarne Stroustrup. In this first example having 2 copies of a base sub-object in the final object type is reasonable:

       struct Link { Link * next; };

       class Task : public Link
       {
       // Link used to maintain list of tasks (the scheduler list)
       };

       class Displayed : public Link
       {
       // Link used to maintain list of all Displayed objects
       // (the display list)
       };

Now we define a Satellite class that is both a task and is displayed:

       class Satellite : public Task, public Displayed
       {
       //...
       };

This is fine - two separate Link objects are used to maintain a Satellite on two separate lists. Stroustrup warns to be careful of ambiguities however - referring to a Link within a Satellite will cause problems - which Link did you mean? So you have to refer to Task or Displayed instead to make it clear which bases' Link you are interested in, for example:

       void mess_with_links( Satellite * p)
       {
         p->next = 0;  // Error: ambiguous - which Link's next?
         p->Link::next = 0;   // Error: ambiguous - which Link?
         p->Task::next = 0;      // OK
         p->Displayed::next = 0; // OK
       }

In the following example a case where have two base sub-objects starts out being a reasonable state of affairs, but after some modifications maintaining the correct behaviour becomes cumbersome.

So, here is the initial version of the class hierarchy:

       class Storable
       {
       public:
         virtual const char * get_file() = 0;
         virtual void read() = 0;
         virtual void write() = 0;
         virtual ~Storable() {}
         // ...
       };

       class Receiver : public Storable
       {
       public:
         void write();
         // ...
       };

       class Transmitter : public Storable
       {
       public:
         void write();
         // ...
       };

       class Radio : public Receiver, public Transmitter
       {
       public:
         const char * get_file();
         void read();
         void write();
         // ...
       };

Here Radio::write, for example, can call its two base implementations then do its own stuff:

       void Radio::write()
       {
         Receiver::write();
         Transmitter::write();
         // Radio specific write stuff...
       };

Again this works because an object can safely and conveniently have more than one Storable sub-object within its make up.

However if, as may well be the case, Storable is updates in some fashion - such as storing the name of the file in the Storable base class, as below:

       class Storable
       {
       public:
         Storable( const char * file_name );
         virtual const char * get_file() = 0;
         virtual void read() = 0;
         virtual void write() = 0;
         virtual ~Storable() {}
         // ...
       private:
         const * char store_file_name;

         Storable( Storable const & );
         Storable & operator=( Storable const & );
       };

Stroustrup points out that this simple little change to Storable means that the design of the Radio class needs to change so that we only have one Storable sub-object in Radio objects rather than the two we had previously to prevent it becoming "unnecessarily hard" to avoid storing multiple copies of the object.

To do this we make Storable a virtual base class of Receiver and Transmitter (note the use of virtual after public in the base class list):

       class Receiver : public virtual Storable
       {
       public:
         void write();
         // ...
       };

       class Transmitter : public virtual Storable
       {
       public:
         void write();
         // ...
       };

       class Radio : public Receiver, public Transmitter
       {
       public:
         void write();
         // ...
       };

This forces Radio to only have one Storable sub-object that is shared by each of the Transmitter and Receiver intermediate base classes.

So rather than looking something like the next diagram which shows the original version of a Radio object without virtual bases (view the using a fixed-space font or the spacing will not work...):

    Storable   Storable
       ^          ^
    Receiver Transmitter
         ^   ^
         Radio

(sorry but diagrams in plain text are difficult !)

We have with the virtual bases, meaning we use virtual inheritance:

         Storable
         ^   ^
    Receiver Transmitter
         ^   ^
         Radio

As you can see the second version of a Radio object's layout differs from the first in that it has only a single Storable sub-object in its make up. This is what virtual inheritance is about.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.