Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple class inheritance?

Tags:

c++

oop

class

Based on the figure below, I wrote my code. enter image description here

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
like image 967
Aan Avatar asked May 04 '26 06:05

Aan


1 Answers

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:

  • Virtual inheritance in C++
  • Virtual Inheritance Confusion
  • Virtual inheritance in C++
  • In C++, what is a virtual base class?

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

like image 77
Nawaz Avatar answered May 06 '26 19:05

Nawaz