class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {};
Why does the dynamic_cast in the following code fail?:
D * pD = new D();
B * pB = pD;
A * pA = pB;
dynamic_cast<A*>(pA);
Assuming what you've written below is only illustrative & your actual
classes do have virtual functions, and you didn't really mean to
dynamic_cast an A* to A*, then the problem is that A is an ambiguous base of
D. The RTTI machinery knows that the underlying object is of type D, so
dynamic_cast to A is required to fail according to 5.2.7/8 of the C++
standard. You can make A an unambiguous base by changing B & C to use
virtual inheritance of A.
If you really meant to dynamic_cast an A* to A*, this is required to work,
according to 5.2.7/3 of the Standard. If it doesn't, it's a bug.
-cd
"Aaron Michalk" <aaronm...@hotmail.com> wrote in message
news:f164f05.02013...@posting.google.com...
assert(dynamic_cast<A*>(pA));
My assert is failing even though pA is of type A* (and points to an
object of type D). My current workaround is to change the assert to:
assert(dynamic_cast<A*>(pA) || dynamic_cast<B*>(pA));
This is messy and the containing code shouldn't have to know about B.
"Carl Daniel" <cpda...@pacbell.net> wrote in message news:<u6oZBKrqBHA.2332@tkmsftngp03>...
Use virtual inheritance :
class A{};
class B : virtual public A{};
class C : virtual public A{};
class D : publicB, public C {};
Arnaud
MVP - VC
The problem seems to be ur lack of virtual inheritance and thus an
amibiguous cast...as Carl points out.
Actually, I wanted to avoid using virtual inheritance because I want
to have an object that behaves like both of the base objects but has
seperate data instances.
Aaron
(FWIW, the behavior mandated by 5.2.7/3 makes this an "insanity check",
since no runtime inspection of the most-derived object should be performed).
-cd
"Jason" <chastel...@hotmail.com> wrote in message
news:u3nq98wqBHA.2564@tkmsftngp04...