C++ multiple inheritance

≯℡__Kan透↙ 提交于 2019-12-08 13:14:31

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. :-)

Everybody has already covered virtual inheritance, but I'd suggest reading the C++ FAQ as well.

http://www.parashift.com/c++-faq-lite/multiple-inheritance.html

You need a virtual inheritance in this case:

#include <iostream>
#include <string>
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 virtual Employee
{
public:
    string getname()
    {
        return ("Manager" + name);
    }
    Manager(string name2) : Employee(name2){}
    Manager() : Employee(){}
};

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

This problem is also known as Diamond inheritance problem: http://en.wikipedia.org/wiki/Diamond_problem

Supervisor contains two objects of type Employee, the direct one and the one over Manager. It is ambiguous to call Employee methods on a Supervisor in consequence (which Employee should be called?). You might want to employ virtual multiple inheritance instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!