- 2072 Chaitra · 5 marks
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:
- Ambiguity -
obj.datacould mean either copy, and the compiler reports an error. - 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)
Related questions
- Pure virtual function and abstract class · Object Oriented Programming, chapter 7 · asked 5×
- Need of virtual function · Object Oriented Programming, chapter 7 · asked 4×
- Virtual destructor with example · Object Oriented Programming, chapter 7
- Abstract Student class program · Object Oriented Programming, chapter 7
- Polygon abstract class with Area() · Object Oriented Programming, chapter 7
- Constructor/destructor order; parameterized base constructor · Object Oriented Programming, chapter 6 · asked 2×
- Need of classless IP addressing · Computer Networks and Security, chapter 4