ArticleslgStudy

computer science

Virtual inheritance

Virtual inheritance is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Virtual inheritance rather than just read about it. In short: Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild derived classes. Without virtual inheritance, if two classes B and C inherit from a class A, and a class D inherits from both B and C, then D will contain two copies of A's member variables: one via B, and one via C.

Virtual inheritance — main illustration
Virtual inheritance — illustration

Key takeaways

  • Virtual inheritance belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Virtual inheritance to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Virtual inheritance from memory before moving on to harder problems.

Reference excerpt

Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild derived classes. Without virtual inheritance, if two classes B and C inherit from a class A, and a class D inherits from both B and C, then D will contain two copies of A's member variables: one via B, and one via C. These will be accessible independently, using scope resolution. Instead, if classes B and C inherit virtually from class A, then objects of class D will contain only one set of the member variables from class A. This feature is most useful for multiple inheritance, as it makes the virtual base a common subobject for the deriving class and all classes that are derived from it. This can be used to avoid the diamond problem by clarifying ambiguity over which ancestor class to use, as from the perspective of the deriving class (D in the example above) the virtual base (A) acts as though it were the direct base class of D, not a class derived indirectly through a base (B or C). It is used when inheritance represents restriction of a set rather than composition of parts. In C++, a base class intended to be common throughout the hierarchy is denoted as virtual with the virtual keyword.

The problem Consider the following class hierarchy.

As declared above, a call to bat.eat() is ambiguous because there are two Animal (indirect) base classes in Bat, so any Bat object has two different Animal base class subobjects. So, an attempt to directly bind a reference to the Animal subobject of a Bat object would fail, since the binding is inherently ambiguous:

To disambiguate, one would have to explicitly convert bat to either base class subobject:

In order to call eat(), the same disambiguation, or explicit qualification is needed: static_cast<Mammal&>(bat).eat() or static_cast<WingedAnimal&>(bat).eat() or alternatively bat.Mammal::eat() and bat.WingedAnimal::eat(). Explicit qualification not only uses an easier, uniform syntax for both pointers and objects but also allows for static dispatch, so it would arguably be the preferable method. In this case, the double inheritance of Animal is probably unwanted, as we want to model that the relation (Bat is an Animal) exists only once; that a Bat is a Mammal and is a WingedAnimal, does not imply that it is an Animal twice: an Animal base class corresponds to a contract that Bat implements (the "is a" relationship above really means "implements the requirements of"), and a Bat only implements the Animal contract once. The real world meaning of "is a only once" is that Bat should have only one way of implementing Eat, not two different ways, depending on whether the Mammal view of the Bat is eating, or the WingedAnimal view of the Bat. (In the first code example we see that Eat is not overridden in either Mammal or WingedAnimal, so the two Animal subobjects will actually behave the same, but this is just a degenerate case, and that does not make a difference from the C++ point of view.) This situation is sometimes referred to as diamond inheritance (see Diamond problem) because the inheritance diagram is in the shape of a diamond. Virtual inheritance can help to solve this problem.

The solution We can re-declare our classes as follows:

The Animal portion of Bat::WingedAnimal is now the same Animal instance as the one used by Bat::Mammal, which is to say that a Bat has only one, shared, Animal instance in its representation and so a call to Bat::Eat is unambiguous. Additionally, a direct cast from Bat to Animal is also unambiguous, now that there exists only one Animal instance which Bat could be converted to. The ability to share a single instance of the Animal parent between Mammal and WingedAnimal is enabled by recording the memory offset between the Mammal or WingedAnimal members and those of the base Animal within the derived class. However this offset can in the general case only be known at runtime, thus Bat must become (vpointer, Mammal, vpointer, WingedAnimal, Bat, Animal). There are two vtable pointers, one per inheritance hierarchy that virtually inherits Animal. In this example, one for Mammal and one for WingedAnimal. The object size has therefore increased by two pointers, but now there is only one Animal and no ambiguity. All objects of type Bat will use the same vpointers, but each Bat object will contain its own unique Animal object. If another class inherits from Mammal, such as Squirrel, then the vpointer in the Mammal part of Squirrel will generally be different to the vpointer in the Mammal part of Bat though they may happen to be the same if the Squirrel class is the same size as Bat.

Additional Example of Several Ancestors This example to illustrates a case where base class A has a constructor variable msg and an additional ancestor E is derived from grandchild class D.

A / \ B C \ / D | E

Here, A must be constructed in both D and E. Further, inspection of the variable msg illustrates how class A becomes a direct base class of its deriving class, as opposed to a base class of any intermediate deriving classed between A and the final deriving class.

Pure Virtual Methods Suppose a pure virtual method is defined in the base class. If a deriving class inherits the base class virtually, then the pure virtual method does not need to be defined in that deriving class. However, if the deriving class does not inherit the base class virtually, then all virtual methods must be defined.

References

Illustrations

Virtual inheritance: Diagram of diamond inheritance, a problem that virtual inheritance is trying to solve.
Diagram of diamond inheritance, a problem that virtual inheritance is trying to solve.
Virtual inheritance illustration

Worked examples

Example 1 — a first encounter with Virtual inheritance

Start with the simplest possible case. Write down what Virtual inheritance claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Virtual inheritance before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Virtual inheritance ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Virtual inheritance

In research
Virtual inheritance appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Virtual inheritance in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Virtual inheritance is common in secondary-school and first-year university syllabi. It links to neighbouring topics C++, Class (computer programming), so understanding it makes those chapters shorter.
In everyday life
Look for Virtual inheritance outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Virtual inheritance” →

How to study Virtual inheritance in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Virtual inheritance means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Virtual inheritance out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Virtual inheritance in simple terms?

Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild derived classes. Without virtual inheritance, if two classes B and C inherit from a class A, and a class D inherits from both B and C, then D will contain two copies of A…

Why does Virtual inheritance matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Virtual inheritance?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Virtual inheritance.

Tags

  • C++
  • Class (computer programming)

Keep exploring