Skip to main content

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.name is 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)

All Object Oriented Programming chapter 6 questions →