0

I have a query regarding the virtual base class. In order to resolve the "dreaded diamond of death" /ambiguity problem in multiple inheritance, virtual base class is introduced.

class A { public: void Foo() {} };
class B : public virtual A {};
class C : public virtual A {};
class D : public B, public C {};

What will happen when a keyword virtual is not used in class C declaration. Could you please explain me in detail?

class A { public: void Foo() {} };
class B : public virtual A {};
class C : public A {};
class D : public B, public C {};
curiousguy
  • 8,038
  • 2
  • 40
  • 58
  • possible duplicate of [In C++, what is a virtual base class?](http://stackoverflow.com/questions/21558/in-c-what-is-a-virtual-base-class) – Björn Pollex Apr 08 '13 at 07:05
  • sidenote: do use composition over inheritence (use the component based design pattern) – Quonux Apr 08 '13 at 08:41
  • "diamond of death" is a problem in C++ multiple inheritance, not in multiple inheritance. – Kaz Jun 17 '13 at 03:13

3 Answers3

3

If your inheritance is not virtual then A members will be present twice in D class.

If A had a field named _a, then, in D, writing B::_a or C::_a would refer to two different memory zones. If your inheritance is virtual then you have only one memory zone.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
Kek
  • 3,145
  • 2
  • 20
  • 26
0

If you are using virtual than there will be no ambiguity when you call foo() using the instance of Class D. and if you are not using virtual than it will be ambiguity.. But be careful that virtual inheritance cost more so use it carefully..

Hitesh Vaghani
  • 1,342
  • 12
  • 31
0
class A { public: void Foo() {} };
class B : public virtual A {};
class C : public A {};
class D : public B, public C {};

If the inheritance from the A class to B marked virtual but not A class to C, then C++ will create a single virtual A (D inherits B, B inherits A) and a nonvirtual A (D inherits C, C inherits A). Therefore, your code will not solve the diamond problem:

D d_object;
A &a_ref = d_object; // error raised -> B::A or C::A
DML
  • 494
  • 5
  • 4