In this post, after introducing two preliminary concepts, I explain what virtual inheritance is, and how it is implemented, then introduce two applications of virtual inheritance. One involves multiple inheritance, and the other involves implementation of non-inheritability. For each case, one example demonstrating how virtual inheritance works is presented.

Some Preliminaries

Before discussing virtual inheritance, it is necessary to explain two very important concepts in OOP (Object Oriented Programming) concepts, static and dynamic binding.

Roughly speaking, static binding occurs at compile time, and dynamic binding occurs at run time. In C++, the two kinds of polymorphism (see Appendix for Classification of Polymorphism), overloading and overriding are two typical examples of these two concepts. For function overloading, when an overloaded function is called, during compile time, the compiler determines which version is actually called by matching their parameter type patterns. Whereas, for function overriding, C++ implements virtual function call resolution with a vtable data structure [4]. In C++, virtual inheritance is also implemented with vtable. Next, we explain what virtual inheritance is, and how it is implemented.

What is “virtual inheritance”? why we need it?

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.

It is well-known that, different from other OOP languages such as Java and C#, C++ supports multiple inheritance, which is complicated, and its necessity is controversial [2]. Virtual inheritance may be required when multiple inheritance is used. For example, diamond problem, which may cause name ambiguity, needs virtual inheritance to be solved when some member function(s) of the common base class is(are) not pure virtual. Next, we explain how virtual inheritance is implemented in C++.

vtable — How “virtual inheritance” is implemented?

Just similar to function overriding, C++ implement virtual inheritance with a vtable data structure. However, it is necessary to notice that different compilers may implement virtual inheritance with vtable in different ways.

For g++ compiler, both virtual functions and virtual base classes share one single vtable. Every instance of a class with virtual inheritance begins with a virtual pointer to the corresponding class.

For MSVC compiler, virtual functions and virtual base classes are stored in separate vtables, and the table for virtual functions is named as vftbl, and the table for virtual base classes is called vbtbl.

#cpp #oops-concepts

Virtual Inheritance
1.40 GEEK