0

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.

Bober02
  • 15,034
  • 31
  • 92
  • 178
  • What have you read about C++ programming? Multiple or virtual inheritance is tricky, and very often should be avoided. And the issue is for a class D inheriting from both B and C. – Basile Starynkevitch Apr 14 '12 at 16:27
  • Well i am studying it now, I only had basic introduction. I would definitely be better off if someone could give a simple example on why you would use one or the other. I don't need any complicated/borderline cases. just basic, typical scenarios would be perfect, in one sentence. – Bober02 Apr 14 '12 at 16:33
  • I very rarely have to use multiple inheritance or virtual inheritance. A good rule is to never use it. – Basile Starynkevitch Apr 14 '12 at 16:48
  • @BasileStarynkevitch "_A good rule is to never use it._" No, a good rule is to use it whenever appropriate. – curiousguy Aug 17 '12 at 23:31

1 Answers1

4

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).

Cœur
  • 37,241
  • 25
  • 195
  • 267
René Richter
  • 3,839
  • 3
  • 34
  • 42