To use dynamic_casting, the inheritance hierarchy needs to be polymorphic. But in the below code segment, dynamic_cast works perfectly for upcasting while it fails at compile time for downcasting? What's the reason upcasting works?
class B{};
class C : public B{};
int main()
{
C* pcob = new C();
B* bp = dynamic_cast<B*>(pcob); // #1 : Upcasting works
if(bp)
cout << "casted" << endl;
else
cout << "bp null" << endl;
delete bp;
B* pbob = new B();
C* pc = dynamic_cast<C*>(pbob); // #2 : Downcasting gives error
if(pc)
cout << "casted" << endl;
else
cout << "pc null" << endl;
delete pbob;
return 0;
}
The compile time error at #2 is
main.cpp: In function ‘int main()’:
main.cpp:36:34: error: cannot dynamic_cast ‘pbob’ (of type ‘class B*’) to type ‘class C*’ (source type is not polymorphic)
C* pc = dynamic_cast<C*>(pbob);