c++ - Type casting issues -
i hava code snippet below:
class classa { public: virtual ~ classa() {}; virtual void functiona() {cout << "classa" << endl;} }; class classb { public: virtual void functionb() {}; }; class classc : public classa, public classb { public: void functiona(){cout << "why" << endl;} void functionb(){cout << "class c funb" << endl;} }; classc aobject; classa* pa = &aobject; classb* pb = &aobject; classc* pc = &aobject; int main() { void* pvoid = static_cast<void *> (pb); classa* pa2 = static_cast<classa*>(static_cast<classc*>(pb)); return 0; }
is type-cast pvoid
, pa2
right? or both of them wrong? (i tried compile it, have not got errors)
pvoid
"right" in sense gives address of classb
subobject of aobject
untyped pointer. useful thing can cast classb*
. note cast here redundant, since pointer can implicitly converted void*
.
pa2
correctly initialised point classa
subobject of aobject
. since "cross-cast" (i.e. neither type derived other, both base classes of derived class), either need convert via derived type you've done, or use dynamic_cast
if derived type not known @ compile time.
Comments
Post a Comment