Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How C++ virtual inheritance is implemented in compilers?

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.

like image 522
MKo Avatar asked Sep 09 '11 11:09

MKo


People also ask

How is virtual inheritance implemented?

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

How virtual inheritance works internally?

Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild derived classes.

What is virtual inheritance describe with an example?

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

How is inheritance implemented in C++?

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.


1 Answers

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.

like image 57
Alex B Avatar answered Sep 21 '22 13:09

Alex B