c++ - Why upcasting works but downcasting gives compile time error? -
to utilize dynamic_casting, inheritance hierarchy needs polymorphic. in below code segment, dynamic_cast works upcasting while fails @ compile time downcasting? what's 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; homecoming 0; }
the compile time error @ #2 is
main.cpp: in function ‘int main()’: main.cpp:36:34: error: cannot dynamic_cast ‘pbob’ (of type ‘class b*’) type ‘class c*’ (source type not polymorphic) c* pc = dynamic_cast<c*>(pbob);
the standard's been quoted - praise be.
to thought why standard specifies behaviour does, helps consider you're asking compiler , how relates mutual implementations of runtime type information....
your dynamic_cast<b*>(pcob)
needs know offset of b
relative containing c
- that's constant amount every c
object, if c
embedded in other object. there's no reliance on unknown until runtime.
contrast dynamic_cast<c*>(pbob)
b* pbob
- compiler can't know whether pointed-to b
embedded in object @ all, allow lone whether object happens - or derived - c
, such cast can succeed. in general, needs rely on runtime type info generated polymorphic types.
in specific code, compiler knows actual types of objects, , little effort have supported downcast, similar code in function gets b*
parameter or calls opaque mill method returning b*
may dynamic_cast
runtime object containing c
, other times not - compiler can't employ "localised" knowledge of real types. in local usage, can create pointers actual runtime type, there's no utility gained requiring compilers back upwards "localised" usage, , standard bans such casts wholesale.
c++ casting
No comments:
Post a Comment