- 2072 Kartik · 6 marks
Hybrid inheritance with example
Short answer
Hybrid inheritance combines multiple inheritance types, like diamond: hierarchical then multiple. Example: class Result inherits Test and Sports, both from Student; using virtual base class avoids duplicate Student sub-objects.
With suitable example explain hybrid inheritance.
Hybrid inheritance is a combination of two or more types of inheritance (single, multilevel, multiple, hierarchical) in one program. A common form is a diamond: hierarchical inheritance followed by multiple inheritance.
Student
/ \
Test Sports
\ /
Result
Test and Sports are derived from Student (hierarchical); Result is derived from both Test and Sports (multiple). Since Result would get two copies of Student, Student is made a virtual base class to avoid ambiguity.
#include <iostream>
using namespace std;
class Student {
protected:
int roll;
public:
void getRoll(int r) { roll = r; }
};
class Test : virtual public Student {
protected:
float m1, m2;
public:
void getMarks(float a, float b) { m1 = a; m2 = b; }
};
class Sports : virtual public Student {
protected:
float score;
public:
void getScore(float s) { score = s; }
};
class Result : public Test, public Sports {
public:
void display() {
cout << "Roll no : " << roll << endl;
cout << "Marks : " << m1 << ", " << m2 << endl;
cout << "Sports : " << score << endl;
cout << "Total : " << m1 + m2 + score << endl;
}
};
int main() {
Result r;
r.getRoll(101);
r.getMarks(70, 80);
r.getScore(10);
r.display();
return 0;
}
Output:
Roll no : 101
Marks : 70, 80
Sports : 10
Total : 160
Here roll is accessed in Result without ambiguity because only one Student sub-object exists.
✓ Answer checked by Claude Opus 5.5 (high effort)