简体   繁体   中英

Virtual Base Class in C++

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 {};

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM