How the compilers implement the virtual inheritance?
In the following code:
class A { public: A(int) {} }; class B : public virtual A { public: B() : A(1) {} }; class C : public B { public: C() : A(3), B() {} };
Does a compiler generate two instance of B::ctor
function, one without A(1)
call, and one with it? So when B::constructor
is called from derived class's constructor the first instance is used, otherwise the second.
According to Wikipedia [1], “virtual inheritance is a technique used in C++, where a particular base class in an inheritance hierarchy is declared to share its member data instances with any other inclusions of that same base in further derived classes.”
Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild derived classes.
Virtual inheritance is used when we are dealing with multiple inheritance but want to prevent multiple instances of same class appearing in inheritance hierarchy. From above example we can see that “A” is inherited two times in D means an object of class “D” will contain two attributes of “a” (D::C::a and D::B::a).
Inheritance in C++ Inheritance is a feature or a process in which, new classes are created from the existing classes. The new class created is called “derived class” or “child class” and the existing class is known as the “base class” or “parent class”. The derived class now is said to be inherited from the base class.
It's implementation-dependent. GCC (see this question), for example, will emit two constructors, one with a call to A(1)
, another one without.
B1() B2() // no A
When B is constructed, the "full" version is called:
B1(): A(1) B() body
When C is constructed, the base version is called instead:
C(): A(3) B2() B() body C() body
In fact, two constructors will be emitted even if there is no virtual inheritance, and they will be identical.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With