Martin T. wrote:
wuguangwen734@hotmail.com wrote:
Here is the class hierarchy:
class A{};
class B:public A {};
class C:public A{};
class D:public B, public C{};
Then, I compiled the following code,
B* pb = new D;
D* pd = dynamic_cast<D*>(pb);
and got the compiler error C2683: 'cast' : 'type' is not a
polymorphic type.
While I changed the definition of class B as:
class B:public A {void virtual f(){}};
the compiler didn't complain any more.
What is the difference? Why the compiler insist on requiring the
the being casted type polymorphic? Dose the existence of multiple
inheritance make difference in this question?
It's got nothing to do with multiple inheritance.
As MSDN states: "C2683 ... You cannot use dynamic_cast to convert
from a non-polymorphic class (a class with no virtual functions)."
The reason is that only if an object has a virtual function (and
thus a virtual function table) is the compiler able to generate
code to determine the actual type of the object at runtime. You
will also need to compile with RTTI (run time type information)
setting:on (which is now on by default I think).