Loay Loay - 1 year ago 49
C++ Question

upcast from indirect multiple inheritance of a base

I have this code:

struct A {};
struct B : A {};
struct C : A {};
struct D : B, C {};

int main(){
D* d;
A* a = d;

The code doesn't compile and I get a compile error:

'A' is an ambiguous base of 'D'

I know that making the inheritance virtual will solve the ambiguity. My question is, why doesn't the upcast work to one of the sub-objects of A ?

Answer Source

Since you have two distinct base subobjects of type A, you need to say which one you want:

A* a_b = static_cast<B*>(d);
A* a_c = static_cast<C*>(d);