Multiple class inheritance?

Based on the figure below, I wrote my code.

This is the code I wrote:

#include<iostream>
#include<string>
using namespace std;

class person
{
private:
    int code;
    string name;
public:
    void    setCode(int c) { code=c; }
    int getCode()          { return code; }
    void setName(string s) { name=s; }
    string getName()       { return name; }
};

class account : public person
{
private:
    double pay;
public:
    void    setPay(double p) { pay=p; }
    double getPay()          { return pay; }
};

class admin : public person
{
private:
    string experience;
public:
    void setExper(string e) { experience=e; }
    string getExper()       { return experience; }
};

class master : public account, public admin
{
};

int main()
{
    master mastObj;// create master object.
    mastObj.setName("John");
    system("pause");//to pause console screen, remove it if u r in linux
    return 0;
}

The compiler showed these errors:

Error   1   error C2385: ambiguous access of 'setName'
Error   2   error C3861: 'setName': identifier not found    
Error   3   IntelliSense: "master::setName" is ambiguous

Answers


You need virtual inheritance:

class account: public virtual person{
....
}

class admin: public virtual  person{
...
}

PS And your pay, code fields lack initialization! This could lead to embarassing errors (like paying the cleaner several million of dollars :)):

#include<iostream>
#include<string>
using namespace std;

class person
{
   // ...
   person() : code(0), name("anonymous") {}

};

class account : public virtual person
{
    // ...
    account() : pay(0) {}
};

class admin : public virtual person
{
    // ...
    admin() : experience("unknown") {}
};

It is classic example of Diamond Problem in C++ when you use multiple inheritance.

The solution is : Virtual inheritance

That is, you should do this:

class account : public virtual person 
{                   //^^^^^^^note this
   //code
};

class admin : public virtual  person
{                  //^^^^^^^note this
   //code
};

I just found really good posts on this site, so I would redirect you to those answers here:

which also means, this topic should be voted for close.


Need Your Help

LazyInitializationException in selectManyCheckbox on @ManyToMany(fetch=LAZY)

jsf jpa primefaces lazy-initialization selectmanycheckbox

What is the best way to handle multiple chackboxes when you nead to fill a JPA M:N relation ... for example I have an JPA entity Hardware and the entity Connectivity.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.