Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base class ambiguous when converting derived class pointer to base class

Tags:

c++

I'm using C++. When I try to convert a derived class' pointer to base class', compiler complains "base class is ambiguous".

I did some research, and found this question How can I avoid the Diamond of Death when using multiple inheritance?. And some other similar issue.

There is a solution, is to use virtual inheritance. But I'm not able to change class definitions, because they are compiled libraries.

Is that possible to do the converting, without changing base class definitions?

A minimal sample would be:

class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {};

What I want to do is:

D *d = new D;
A *a = (D *)d;  // ambiguous
like image 963
zhm Avatar asked Sep 03 '25 09:09

zhm


1 Answers

Is that possible to do the converting, without changing base class definitions?

Yes it is. You have to choose which direct base class to go through.

class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {};

void foo(A&) {}

int main() {
    D d;

    foo(static_cast<B&>(d));
    foo(static_cast<C&>(d));

    return 0;
}
like image 89
StoryTeller - Unslander Monica Avatar answered Sep 05 '25 00:09

StoryTeller - Unslander Monica