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 ";
}
};
class 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?