Loading lessons...
Using Multiple Inheritance: The Diamond Problem & Virtual Base Classes
Using Multiple Inheritance: The Diamond Problem & Virtual Base Classes
Multiple inheritance (Lesson 23) lets a class combine several base classes. It is powerful but brings two problems: name ambiguity between bases, and the diamond problem, where a class inherits the same grandparent twice.
C++ solves the diamond with virtual base classes. This lesson shows when multiple inheritance is useful, what goes wrong, and how to use it safely.
1. When Multiple Inheritance Is Useful
| Use | Example |
|---|---|
| Combining independent capabilities | class Amphibian : public LandVehicle, public WaterVehicle |
| Implementing several interfaces (abstract classes) | class File : public Readable, public Writable |
| Mixing in a utility class | class Logger mixed into many classes to add logging |
| Modelling objects that genuinely are two things | a TeachingAssistant is both a Student and a Teacher |
The standard library itself uses it: iostream is derived from both istream and ostream (Lesson 35).
2. Ambiguity from Same-Named Members
If two base classes have members with the same name, using that name through the derived class is ambiguous. Resolve it with the scope resolution operator or by redefining the member in the derived class (shown in Lesson 23).
#include <iostream>
using namespace std;
class Printer {
public:
void start() {
cout << "Printer warming up" << endl;
}
};
class Scanner {
public:
void start() {
cout << "Scanner calibrating" << endl;
}
};
class AllInOne : public Printer, public Scanner {
public:
void start() { // redefine to remove the ambiguity
Printer::start();
Scanner::start();
}
};
int main() {
AllInOne device;
device.start();
device.Scanner::start(); // or choose one explicitly
return 0;
}Output:
Printer warming up
Scanner calibrating
Scanner calibrating3. The Diamond Problem
Consider Student as a base class, Test and Sports both derived from it, and Result derived from both Test and Sports. The inheritance graph looks like a diamond.
The diamond: Result inherits Student through Test and through Sports
Result inherits the members of Student twice, once through each path. A Result object contains two copies of Student's data, so a reference such as rollNumber is ambiguous: which copy is meant? The two copies can also hold different values, which makes no sense for one student.
class Student {
protected:
int rollNumber;
};
class Test : public Student {};
class Sports : public Student {};
class Result : public Test, public Sports {
void f() {
// rollNumber = 5; // error: ambiguous (two copies)
Test::rollNumber = 5; // legal but awkward: two separate copies exist
}
};4. Virtual Base Classes
The fix is to declare the common base class virtual when the intermediate classes inherit from it. Then C++ keeps only one copy of the virtual base in any object, however many paths lead to it.
class Test : virtual public Student {}; // the keywords may be in either order:
class Sports : public virtual Student {}; // "virtual public" = "public virtual"The complete program, with Student as a virtual base class of both Test and Sports:
#include <iostream>
using namespace std;
class Student {
protected:
int rollNumber;
public:
void getNumber(int a) {
rollNumber = a;
}
void putNumber() {
cout << "Roll No: " << rollNumber << endl;
}
};
class Test : virtual public Student { // virtual base
protected:
float part1, part2;
public:
void getMarks(float x, float y) {
part1 = x;
part2 = y;
}
void putMarks() {
cout << "Marks obtained:" << endl;
cout << " Part 1 = " << part1 << endl;
cout << " Part 2 = " << part2 << endl;
}
};
class Sports : public virtual Student { // virtual base
protected:
float score;
public:
void getScore(float s) {
score = s;
}
void putScore() {
cout << "Sports weight: " << score << endl;
}
};
class Result : public Test, public Sports { // only ONE Student inside
float total;
public:
void display() {
total = part1 + part2 + score;
putNumber(); // no ambiguity now
putMarks();
putScore();
cout << "Total Score: " << total << endl;
}
};
int main() {
Result student1;
student1.getNumber(678);
student1.getMarks(30.5, 25.5);
student1.getScore(7.0);
student1.display();
cout << "One Student sub-object? "
<< (static_cast<Student*>(static_cast<Test*>(&student1)) ==
static_cast<Student*>(static_cast<Sports*>(&student1)))
<< endl;
return 0;
}Output:
Roll No: 678
Marks obtained:
Part 1 = 30.5
Part 2 = 25.5
Sports weight: 7
Total Score: 63
One Student sub-object? 1Both paths now lead to the same Student sub-object, as the last line confirms.
5. Constructors with Virtual Base Classes
With a virtual base there is only one base sub-object, but two intermediate classes might each try to initialise it with different arguments. C++ settles this with two rules:
- The most derived class (the one actually being created) calls the virtual base's constructor directly, in its own initialization list. Calls to the virtual base's constructor from the intermediate classes are ignored when they are not the most derived class.
- Virtual base classes are constructed first, before any non-virtual base, regardless of the declaration order.
#include <iostream>
using namespace std;
class Person {
protected:
int id;
public:
Person(int i) : id(i) {
cout << "Person(" << i << ")" << endl;
}
};
class Faculty : virtual public Person {
public:
Faculty(int i) : Person(i) {
cout << "Faculty" << endl;
}
};
class Student : virtual public Person {
public:
Student(int i) : Person(i) {
cout << "Student" << endl;
}
};
class TA : public Faculty, public Student {
public:
TA(int i) : Person(i), Faculty(i + 100), Student(i + 200) { // TA builds Person itself
cout << "TA" << endl;
}
void show() {
cout << "TA id = " << id << endl;
}
};
int main() {
TA t(7);
t.show();
return 0;
}Output:
Person(7)
Faculty
Student
TA
TA id = 7Person is built once, first, with the value TA passed (7). The values 107 and 207 passed by Faculty and Student are ignored for the virtual base.
6. Normal vs Virtual Base Class
| Normal base (in a diamond) | Virtual base |
|---|---|
class B : public A | class B : virtual public A |
one copy of A per path | one shared copy of A |
ambiguous access to A's members | unambiguous access |
| each intermediate class initialises its own copy | the most derived class initialises the single copy |
| constructed in declaration order | constructed before all non-virtual bases |
| no extra overhead | small overhead: an extra pointer or offset to find the shared base |
7. Guidelines for Using Multiple Inheritance
- Use it when a class genuinely is two independent things, or to combine abstract interfaces.
- If two bases share a common ancestor, make that ancestor a virtual base.
- Resolve name clashes explicitly with
Base::name, or redefine the member. - Avoid deep diamonds; consider composition instead if the "is-a" test is doubtful.
Key points to remember
- Multiple inheritance:
class C : public A, public B; useful for combining interfaces or capabilities. - Same-named members in two bases: use
A::f()or redefinefin the derived class. - Diamond problem: the grandparent is inherited twice, giving two copies and ambiguity.
- Fix:
class B : virtual public Aon each intermediate class; only one shared copy remains. - The most derived class constructs the virtual base, and virtual bases are constructed first.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What is a virtual base class? Explain the diamond problem and how virtual base classes solve it, with a program. (10 Marks)
- Write: the diamond diagram, the two copies and the ambiguity, the
virtual publicsyntax, and theStudent/Test/Sports/Resultprogram with output. - Q2. How are constructors called when a virtual base class is involved? (5 Marks)
- Write: the two rules and the
Person/Faculty/Student/TAprogram. - Q3. Explain ambiguity resolution in multiple inheritance. (2.5 Marks)
- Q4. Differentiate between a normal base class and a virtual base class. (2.5 Marks)