virtual inheritance [duplicate]

倖福魔咒の 提交于 2019-12-17 07:12:19

问题


What is the meaning of "virtual" inheritance?

I saw the following code, and didn't understand the meaning of the keyword virtual in the following context:

class A {};
class B : public virtual A;

回答1:


Virtual inheritance is used to solve the DDD problem (Dreadful Diamond on Derivation).

Look at the following example, where you have two classes that inherit from the same base class:

class Base
{

public:

 virtual void  Ambig();

};

class C : public Base
{

public:

//...

};

class D : public Base
{
public:

    //...

};

Now, you want to create a new class that inherits both from C and D classes (which both have inherited the Base::Ambig() function):

class Wrong : public C, public D
{

public:

...

};

While you define the "Wrong" class above, you actually created the DDD (Diamond Derivation problem), because you can't call:

Wrong wrong;
wrong.Ambig(); 

This is an ambiguous function because it's defined twice:

Wrong::C::Base::Ambig()

And:

Wrong::D::Base::Ambig()

In order to prevent this kind of problem, you should use the virtual inheritance, which will know to refer to the right Ambig() function.

So - define:

class C : public virtual Base

class D : public virtual Base

class Right : public C, public D


来源:https://stackoverflow.com/questions/419943/virtual-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!