- Asked 2/10
- 2069 Chaitra · 2+4 marks
- 2068 Chaitra · 3 marks
Multipath inheritance problem and solution
Short answer
Multipath inheritance (diamond problem) causes a derived class to inherit multiple copies of a common base class, leading to ambiguity and inconsistency. The solution is to declare the common base as virtual in intermediate classes, ensuring only one shared copy.
What kind of problem is encountered in multipath inheritance? Write down its solution with suitable example.
Multipath inheritance occurs when a derived class inherits from the same base class through more than one path. For example, Parent1 and Parent2 are both derived from Grandparent, and Child is derived from both Parent1 and Parent2. This diamond-shaped hierarchy is a form of hybrid inheritance.
Person
/ \
Student Employee
\ /
Intern
Problem
Intern gets two copies of Person's members: one through Student and one through Employee. Then:
- An access such as
obj.nameis ambiguous, and the compiler gives an error. - Memory is wasted by the duplicate copies, and the data may become inconsistent.
Solution: virtual base class
Declare the common base as virtual in the intermediate classes. Then only one shared copy of Person is inherited.
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
string name;
};
class Student : virtual public Person { };
class Employee : virtual public Person { };
class Intern : public Student, public Employee { };
int main() {
Intern i;
i.name = "Hari"; // no ambiguity: one copy only
cout << i.name << endl;
return 0;
}
Output: Hari
Without virtual, i.name would fail to compile; it would need i.Student::name or i.Employee::name, referring to two different copies.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Effect of derivation types on class members · Object Oriented Programming, chapter 6
- TOH problem with solution for n disks · Data Structure and Algorithm, chapter 5 · asked 2×
- Dining philosophers problem and solution · Operating System, chapter 3 · asked 2×
- Top-down integration problems; regression testing · Software Engineering, chapter 8
- Galerkin and collocation solution of an ODE · Finite Element Method, chapter 4