Forms of Inheritance, The Diamond Problem & Virtual Base Classes
1. The Five Forms of Inheritance in C++ (In Simple Words)
In C++, you can link classes together in 5 different ways:
The 5 Forms of Inheritance
1. Single Inheritance
One child class inherits from one parent class.
Class A ──▶ Class B2. Multilevel Inheritance
A chain of inheritance (Grandfather ──▶ Father ──▶ Son).
Class A ──▶ Class B ──▶ Class C3. Multiple Inheritance
One child class inherits from two or more parent classes.
Class A + Class B ──▶ Class C4. Hierarchical Inheritance
One parent class is inherited by multiple child classes.
Class A ──▶ Class B & Class C5. Hybrid Inheritance
A mix of two or more inheritance types (e.g. Hierarchical + Multiple forming a diamond shape).
2. Ambiguity in Multiple Inheritance
In Multiple Inheritance, a child class inherits from two parent classes.
What happens if both parent classes have a function with the exact same name?
class Father {
public:
void advise() { cout << "Study hard!" << endl; }
};
class Mother {
public:
void advise() { cout << "Eat healthy food!" << endl; }
};
class Child : public Father, public Mother {
// Inherits TWO identical advise() functions!
};
int main() {
Child c;
// c.advise(); // 💥 COMPILER ERROR: Which advise() should I call? Father's or Mother's?
// THE SOLUTION: Use the Scope Resolution Operator (::)
c.Father::advise(); // Calls Father's version
c.Mother::advise(); // Calls Mother's version
return 0;
}
3. The Diamond Problem in Hybrid Inheritance
The most famous inheritance problem in C++ exams is the Diamond Problem (Multipath Inheritance):
┌───────────────┐
│ Class A: GP │ (Grandparent: contains int rollNo)
└───────┬───────┘
│
┌─────────────┴─────────────┐
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ Class B: Parent │ │ Class C: Parent │
└────────┬────────┘ └────────┬────────┘
│ │
└─────────────┬─────────────┘
▼
┌───────────────┐
│ Class D: Child│ (Receives TWO duplicate copies of 'rollNo'!)
└───────────────┘
Why is it a problem?
Class BinheritsClass A, so it gets a copy ofrollNo.Class Calso inheritsClass A, so it gets another copy ofrollNo.- Now
Class Dinherits from bothClass BandClass C. - As a result,
Class Dgets TWO DUPLICATE COPIES ofrollNo! - When you write
objD.rollNo = 101;, the compiler throws an error: “Ambiguous request for rollNo! Which copy do you want to modify?”
4. The Solution: Virtual Base Classes
To fix this duplicate copy bug, C++ gives us Virtual Base Classes.
When classes B and C inherit from A, we add the virtual keyword:
“Hey C++, make sure only ONE SINGLE shared copy of Class A is passed down to all future child classes!”
Syntax:
class B : virtual public A { ... };
class C : virtual public A { ... };
class D : public B, public C { ... };
5. Complete Working C++ Program: The Diamond Solution
#include <iostream>
using namespace std;
// 1. GRANDPARENT BASE CLASS
class Student {
protected:
int rollNo;
public:
void setRoll(int r) { rollNo = r; }
void printRoll() const { cout << "Roll No: " << rollNo << endl; }
};
// 2. PARENT 1: Virtual inheritance prevents duplicate copy
class Test : virtual public Student {
protected:
float part1, part2;
public:
void setMarks(float m1, float m2) { part1 = m1; part2 = m2; }
};
// 3. PARENT 2: Virtual inheritance prevents duplicate copy
class Sports : virtual public Student {
protected:
float score;
public:
void setScore(float s) { score = s; }
};
// 4. CHILD CLASS: Inherits from both Test and Sports
class Result : public Test, public Sports {
private:
float total;
public:
void display() {
total = part1 + part2 + score;
// Roll number has ONLY 1 copy! Zero ambiguity!
printRoll();
cout << "Exam Marks : " << part1 << " + " << part2 << endl;
cout << "Sports Score: " << score << endl;
cout << "Total Grade : " << total << endl;
}
};
int main() {
Result studentResult;
studentResult.setRoll(101); // Works perfectly without any ambiguity!
studentResult.setMarks(75.0f, 80.0f);
studentResult.setScore(15.0f);
studentResult.display();
return 0;
}
6. Order of Constructor Execution in Inheritance
When you create an object of a derived class:
- Virtual Base Class constructors run FIRST.
- Then, normal Base Class constructors run in order from left to right as listed in the class header.
- Finally, the Derived Class constructor runs last.
DAVV Exam Preparation Tips
Frequently Asked 5-Mark Questions:
- Explain the 5 forms of inheritance with neat diagrams.
Model Answer:- Draw simple block diagrams for: Single, Multilevel, Multiple, Hierarchical, and Hybrid.
- Write 1 line of explanation and syntax for each.
- How do you resolve function name ambiguity in Multiple Inheritance?
Model Answer:- Explain using the Scope Resolution Operator:
obj.Father::advise();andobj.Mother::advise();.
- Explain using the Scope Resolution Operator:
Frequently Asked 10-Mark Questions:
- What is the Diamond Problem in Hybrid Inheritance? How is it resolved using Virtual Base Classes? Write a complete C++ program modeling a Student academic and sports evaluation system.
Model Answer:- Draw the classic Diamond shape diagram (
Student→Test&Sports→Result). - Explain why duplicate copies of data members cause compiler ambiguity errors.
- Explain the
virtual publickeyword and how it ensures only a single shared copy is inherited. - Write out the complete C++ program with classes
Student,Test,Sports, andResult.
- Draw the classic Diamond shape diagram (