Codementor Events

Regular Inheritance VS Virtual Inheritance in C++

Published May 21, 2025

🧬 Regular Inheritance vs. Virtual Inheritance in C++ (With Examples)

In object-oriented programming, inheritance allows us to build a hierarchy of classes where derived classes can reuse the functionality of base classes. However, in C++, multiple inheritance can sometimes lead to a classic issue, the Diamond Problem. To solve this, C++ provides virtual inheritance.
In this post, we'll explore:

  1. What regular inheritance is
  2. The Diamond Problem with multiple inheritance
  3. How virtual inheritance solves the problem
  4. Code examples for clarity

🌳 Regular Inheritance

In regular inheritance, each base class is inherited normally, and no special treatment is given to shared base classes.

Example

#include <iostream>
using namespace std;

class A {
public:
    void show() { cout << "Class A\n"; }
};
class B : public A {};
class C : public A {};
class D : public B, public C {};
int main() {
    D obj;
    // obj.show(); // ❌ Ambiguity: Which A::show() to call?
}

What's the problem?

In the above example, class D inherits from both B and C, and both B and C inherit from A. This leads to two separate copies of the class A inside D, causing ambiguity:
error: request for member 'show' is ambiguous
You could fix it manually like:

obj.B::show();
obj.C::show();

But that defeats the purpose of clean inheritance.

💡 Virtual Inheritance

To solve the duplication and ambiguity problem, C++ allows virtual inheritance. This tells the compiler that shared base classes should be merged into a single instance.
Modified Example Using Virtual Inheritance

#include <iostream>
using namespace std;

class A {
public:
    void show() { cout << "Class A\n"; }
};
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};
int main() {
    D obj;
    obj.show();  // ✅ No ambiguity now!
}

How does it work?

Now D contains only one shared instance of A. The The virtual keyword ensures that both B and C Refer to the same base A.

🧠 When to Use Virtual Inheritance?

Use virtual inheritance when:

  1. You expect a class to be inherited multiple times in a hierarchy.
  2. You want to avoid duplication of the same base class.
  3. You're dealing with complex class relationships like mixins or interfaces.

✅ Summary

Feature Regular Inheritance Virtual Inheritance Base class instances Multiple (in diamond) Single (shared) Ambiguity Possible Resolved Use case Simple hierarchies Multiple inheritance scenarios


🔚 Final Thoughts

While virtual inheritance may seem like an advanced concept, it's a powerful tool when building complex class hierarchies. Understanding how and when to use it can save you hours debugging ambiguous or duplicated behavior.
Let me know in the comments: Have you ever run into the Diamond Problem in your projects? How did you solve it?

Discover and read more posts from Kazi Sohan
get started