Search code examples
c++inheritancemultiple-inheritancediamond-problem

C++ multiple inheritance


Please don't question the really odd hierarchy of workers in this code here, I have no idea why anyone would want something like this, but I decided to give myself an exercise in Multiple Inheritance, just to be sure I fully understood it. So here's the result.

using namespace std;

class Employee
{
protected:
    string name;
public:
    string getname()
    {
        return name;
    }
    void setname(string name2)
    {
        name = name2;
    }
    Employee(string name2)
    {
        name = name2;
    }
    Employee(){}
};

class Manager : public Employee
{
public:
    string getname()
    {
        return ("Manager" + name);
    }
    Manager(string name2) : Employee(name2){}
    Manager() : Employee(){}
};

class Supervisor : public Manager,public Employee
{
public:
    Supervisor(string name2) : Manager(name2) , Employee(name2){}
    Supervisor() : Manager() , Employee(){}
    string getname()
    {
        return ("Supervisor" + Employee::getname());
    }
};

Hopefully you're understanding what I'm trying to do here. I'm getting something about an "ambiguous conversion between derived class 'Supervisor' and base class 'Employee.'" So what do I do?


Solution

  • Actually, the way you have defined Supervisor class, its object will have two subjects of type Employee, each coming from it base classes. That is causing problem.

    The solution is to use virtual inheritance (assuming you need multiple inheritance) as:

    class Manager : public virtual Employee 
    

    Hope you note the virtual keyword here. :-)