How to solve diamond issue in C++?

962 Views Asked by At

I have following test program

#include<iostream>
using namespace std;


class Faculty {
// data members of Faculty
public:
    Faculty(int x) {
    cout<<"Faculty::Faculty(int ) called"<< endl;
    }
    void test() {
        cout<<"Faculty::test called" << endl;
    }
};

class Student  {
// data members of Student
public:
    Student(int x) {
        cout<<"Student::Student(int ) called"<< endl;
    }
    void test() {
        cout<<"Student::test called" << endl;
    }
};

class TA : virtual public Faculty, virtual public Student {
public:
    TA(int x):Student(x), Faculty(x) {
        cout<<"TA::TA(int ) called"<< endl;
    }
};

int main() {
    TA ta1(30);
    ta1.test();
}

An errors is getting during compilation

8be257447d8c26ef785b1a60f2884a.cpp: In function 'int main()':
748be257447d8c26ef785b1a60f2884a.cpp:36:6: error: request for member 'test' is ambiguous
  ta1.test();
      ^
748be257447d8c26ef785b1a60f2884a.cpp:22:7: note: candidates are: void Student::test()
  void test() {
       ^
748be257447d8c26ef785b1a60f2884a.cpp:11:7: note:                 void Faculty::test()
  void test() {
       ^ 

Even I'm using virtual inheritance here. Any solution to this?

2

There are 2 best solutions below

0
On BEST ANSWER

There is no need of virtual keyword here, classes Student and Faculty are not related via inheritance from common class.

If you want specific method to be used in TA you can put using Student::test; or using Faculty::test; inside TA class declaration.

I hope that this example appeared from purely educational purposes, because if it's used/planned to be used in real application - it's a sign of something's going wrong with design :)

0
On

You simply have two test() methods in your TA class, one inherited from Faculty, the other one from Student, and compiler correctly informs you it can't decide which one you want to call.

You need to resolve that either by saying explicitly which method you want to invoke:

TA ta1(30);
ta1.Faculty::test();

or how the object should be treated (and that will imply which method to call):

((Faculty &)ta1).test();