Search code examples
c++multiple-inheritancevirtual-inheritance

virtual vs non-virtual multiple inheritance in c++


I am currenlty trying to grasp the concept of multiple virtual/non-virtual inheritance in c++. if I understand correctly if a class B and C inherit virtually from class A, they share a kind of singleton object i.e. they both access same fields of one common object A. Multiple inheritance would create separate A objects for any B and C object.

Taking above into consideration, would anyone be so kind and present it in a simple, practical context? Why mutiple inheritance in the first place and then why virtual/non-virtual?

Thanks.


Solution

  • Multiple inheritance is not often used in C++. In most cases it's a mixin of interface / implementation. It's not forbidden, also. The need for (virtual) multiple inheritance comes from design decisions to derive from one general base class:

    class Window 
    { /* draw, show, hide, background ... */ };
    
    class WindowWithBorder : public virtual Window 
    { /* methods to manipulate / draw border ... */ };
    
    class WindowWithMenu : public virtual Window
    { /* methods to manipulate / draw Menu ... */ };
    
    class MyWindow : public WindowWithBorder, public WindowWithMenu
    { /* now it's your turn ... */ };
    

    Those diamond-shaped inheritance graphs must be foreseen by the library implementer. Without virtual there would be two base Window objects, with virtual it's only one, but not a singleton, since there can be many windows.

    Libraries can often (but not in every case) avoid such situations, e.g. by implementing a composite design pattern, having a "fat" base class, by implementing abstract interface classes, or by using templates with traits / policies.

    I would recommend to read the chapter on class hierarchies in Bjarne Stroustrup's The C++ Programming language (ch. 15 in my 3rd edition, I borrowed the example from).