C++ dynamic_cast Casting Instances Dynamically
#include <iostream> #include <string> using namespace std; class King/*from ww w.j a v a2 s. co m*/ { protected: string CrownName; public: virtual string &MyName() { return CrownName; } virtual ~King(){} }; class Prince : public King { public: string School; }; void KingInfo(King *inst) { cout << inst->MyName() << endl; Prince *asPrince = dynamic_cast<Prince *>(inst); if (asPrince != 0){ cout << asPrince->School << endl; } } int main() { Prince g; g.MyName() = "fdsa"; g.School = "test test test"; KingInfo(&g); King Henry; Henry.MyName() = "new name"; KingInfo(&Henry); return 0; }