So I was wondering why the following code snippet of the diamond problem is not able to be compiled. I am aware that this problem is usually solved by virtual inheritance, i didn't use this on purpose. The code is just to showcase my question on why the compiler calls this ambiguous: So i have two member variables declared in struct Base, because the two subclasses (in this case structs) do not inherit virtually, i would have a reference to the Base members in each derived struct. Now I have another struct AllDer which would run in the problem of knowing id_ and name_ two times. However when i explicitly target id_ and name_ from Base, i don't understand why this would be ambiguous since the direct target variable is specified through the ::-operator.
cout << Der1::Base::id_ << Der1::Base::name_ << '\n';
Can somebody tell me, why the compiler runs into a problem here? (Please forgive possibly wrong technical terms) Compiler error message says: "ambiguous conversion from derived class 'AllDer' to base class". Using MinGW 7.3.0 64-bit for C++ in QT Creator.
EDIT: Since this problem seems to get handled differently by compilers, please check the linked question.
#include <string>
#include <iostream>
using std::string; using std::cout;
struct Base
{
int id_;
string name_; //target members for readAllDer() in AllDer
void read()
{
cout << id_ << ' ' << name_ << '\n';
}
};
struct Der1 : public Base
{
//Der1 has own reference to id_, name_
void readDer1()
{
cout << id_ << name_ << '\n';
}
};
struct Der2 : public Base
{
//Der2 has own reference to id_, name_
void readDer2()
{
cout << id_ << name_ << '\n';
}
};
//
struct AllDer : public Der1, public Der2
{
void readAllDer()
{
cout << Der1::Base::id_ << Der1::Base::name_ << '\n'; // Why is this ambiguous?
}
};