←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Forms of Inheritance, The Diamond Problem & Virtual Base Classes

Study material and explanations for Unit 5

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 B
2. Multilevel Inheritance
A chain of inheritance (Grandfather ──▶ Father ──▶ Son).
Class A ──▶ Class B ──▶ Class C
3. Multiple Inheritance
One child class inherits from two or more parent classes.
Class A + Class B ──▶ Class C
4. Hierarchical Inheritance
One parent class is inherited by multiple child classes.
Class A ──▶ Class B & Class C
5. 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?

  1. Class B inherits Class A, so it gets a copy of rollNo.
  2. Class C also inherits Class A, so it gets another copy of rollNo.
  3. Now Class D inherits from both Class B and Class C.
  4. As a result, Class D gets TWO DUPLICATE COPIES of rollNo!
  5. 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:

  1. Virtual Base Class constructors run FIRST.
  2. Then, normal Base Class constructors run in order from left to right as listed in the class header.
  3. Finally, the Derived Class constructor runs last.

DAVV Exam Preparation Tips

Frequently Asked 5-Mark Questions:

  1. 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.
  2. How do you resolve function name ambiguity in Multiple Inheritance?
    Model Answer:
    • Explain using the Scope Resolution Operator: obj.Father::advise(); and obj.Mother::advise();.

Frequently Asked 10-Mark Questions:

  1. 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 public keyword and how it ensures only a single shared copy is inherited.
    • Write out the complete C++ program with classes Student, Test, Sports, and Result.