Skip to main content

Need of virtual base class

Short answer

In diamond inheritance, a base class is inherited multiple times causing ambiguity and duplication. Declaring the intermediate classes with virtual base ensures only one shared sub-object; the most derived class constructs it, resolving ambiguity.

Explain the need of virtual base class with suitable example.

A virtual base class is a base class declared with the keyword virtual in the derived classes' inheritance list, so that when it is inherited through multiple paths, only one shared copy of it is present in the final derived class.

Need

In multipath (diamond) inheritance, the final class inherits the common base twice - once through each intermediate class. This creates:

  1. Ambiguity - obj.data could mean either copy, and the compiler reports an error.
  2. Duplication - two copies waste memory and can hold different values.
          Person              (inherited twice without virtual)
          /    \
     Student  Employee
          \    /
          Intern

Example - without virtual (error)

class Person { public: int id; };
class Student : public Person {};
class Employee : public Person {};
class Intern : public Student, public Employee {};
// Intern x;  x.id = 5;   // error: request for 'id' is ambiguous

Example - with virtual (works)

#include <iostream>
using namespace std;

class Person {
public:
    int id;
};
class Student : virtual public Person {};     // virtual
class Employee : virtual public Person {};    // virtual
class Intern : public Student, public Employee {};

int main() {
    Intern x;
    x.id = 5;                    // one copy of id, no ambiguity
    cout << "id = " << x.id << endl;
    return 0;
}

Output: id = 5

virtual must be written in the intermediate classes Student and Employee, not in Intern. The most derived class constructs the shared virtual base first.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 6 questions →