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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With