From https://en.cppreference.com/w/cpp/language/dynamic_cast:
dynamic_cast < new_type > ( expression )
3) If
new_type
is a pointer or reference to Base, and the type ofexpression
is a pointer or reference to Derived, where Base is a unique, accessible base class of Derived, the result is a pointer or reference to the Base class subobject within the Derived object pointed or identified byexpression
. (Note: an implicit conversion andstatic_cast
can perform this conversion as well.)
Sample code:
#include <iostream>
using namespace std;
class A {
//public:
// virtual ~A() {
//
// }
};
class B : public A {
};
class C : public B {
};
class D : public B, public A {
};
int main()
{
D* pd = new D;
if (B* pa = dynamic_cast<B*>(pd)) {
cout << "1";
}
return 0;
}
No error or warning under VC++
warning: direct base 'A' inaccessible in 'D' due to ambiguity
under gcc, link
Shouldn't I expect a compile error?
Now I find that if I try to convert D*
to A*
, a error would occur, but as mentioned above, from D*
to B*
, no error.
int main()
{
D* pd = new D;
if (A* pa = dynamic_cast<A*>(pd)) {
cout << "1";
}
return 0;
}
B
in Your example unique base class ofD
? No wonder it compiles – bartopB
withinD
, so there is no reason to expect an error fromdynamic_cast<B*>(pd)
. VC++ is being kind to you, by warning thatA
is an ambiguous base ofD
, but since there is no attempt to convert aD *
to anA*
, there is no diagnosable error. In the second case,dynamic_cast<A*>(pd)
, there is a diagnosable error, since the conversion is ambiguous. In short: both compilers are correct, but VC++ gives an additional warning. Compilers are not required to give warnings. – Peter