Inheritance Forms, Virtual Base Classes & The Diamond Problem
Idea in plain words
Derivation modes: public (public->public, protected->protected), protected (public & protected -> protected), private (all become private).
Exam tip
High-yield exam topic (Very High).
Explanation
Inheritance establishes 'is-a' relationships. In multipath multiple inheritance, duplicated ancestor copies create memory bloat and compiler ambiguity. C++ resolves this via Virtual Base Classes, where the compiler synthesizes an internal virtual base pointer table (vbtable), binding derived instances to a single shared ancestor subobject in memory.
Key points
- Inheritance types: Single, Multilevel, Multiple, Hierarchical, Hybrid.
- The Diamond Problem: Arises in multipath multiple inheritance where Class D inherits from Class B and C, which both inherit from Class A. D receives two conflicting copies of A's members.
- Virtual Base Classes: Class B : virtual public A and Class C : virtual public A ensures that Class D inherits only ONE shared instance of Class A.
- Constructors in Inheritance: Base constructors execute first, followed by derived constructors. In virtual inheritance, the most derived class directly calls the virtual base constructor.
Example
Example
Member initialization list passes arguments to base constructors: Derived(int a, int b) : Base(a), derivedVal(b) {}.
Code examples
// Resolving The Diamond Problem Using Virtual Base Classes in C++
#include <iostream>
using namespace std;
class Student {
protected:
int rollNumber;
public:
void setRoll(int r) { rollNumber = r; }
};
class Test : virtual public Student {
protected:
float marks1, marks2;
public:
void setMarks(float m1, float m2) { marks1 = m1; marks2 = m2; }
};
class Sports : virtual public Student {
protected:
float score;
public:
void setScore(float s) { score = s; }
};
class Result : public Test, public Sports {
public:
void display() {
// No ambiguity! Exactly one copy of rollNumber exists
float total = marks1 + marks2 + score;
cout << "Roll: " << rollNumber << ", Total: " << total << endl;
}
};
Exam questions
- [8 Marks] What is the diamond problem in C++? Explain with an inheritance diagram how virtual base classes resolve member duplication.
- [7 Marks] Explain the visibility of base class members under public, protected, and private derivation modes.
- [7 Marks] Write a program demonstrating constructor call sequences in multiple and multilevel inheritance.