开发者

what is virtual inheritance in c++

Suppose I have this code:

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

class D: public B,public C, virtual public A {
};

If D inherits B and C, virtual inheritance can ensure there is only one copy of A contained in D; but what if D inherits A using virtual public A again, like in the code above?

Will there be one sub-object of type A, or two?


I am still confused about some expressions with virtual inheritance. for example:

#include <iostream>
using namespace std;

class A {
    public:
    A() {std::cout<<"A ";}
};

class B: A {
    public:
    B() {std::cout<<"B ";}
};

class AToo: virtual A {
    public:
    AToo() {
    std::cout<<"AToo ";
}
};

cl开发者_开发百科ass ATooB: virtual AToo, virtual B {
    public: 
    ATooB() {
    std::cout<<"ATooB ";
}
};

can the virtual keyword ensure that there is only one copy of A in ATooB? if AToo inherits from A using virtual inheritance, but B does not, what will happen? Will there be two copies in ATooB? Does this imply that both B and AToo should use virtual inheritance for A in order to ensure that ATooB has only one copy?


One - that's the intended use of virtual inheritance. There is only one copy of A.

You can actually verify that easily. Give A a member and modify it using a D instance. If there was more than one copy of A, the compiler would say that the access is ambiguous.

Edit in the edited question, there will be two copies of A. Each time A is inherited regularly (without virtual), a fresh copy of A is made. If you want one copy, declare it virtual every time.


From standard docs., 10.1.4,

... For each distinct base class that is specified virtual, the most derived object shall contain a single base class subobject of that type. ....

And so yes, just one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜