Casting Instances Dynamically for Safety - C++ Class

C++ examples for Class:object

Description

Casting Instances Dynamically for Safety

Demo Code

#include <iostream>
#include <string>

using namespace std;

class King/*w  w w. j  av  a  2s.com*/
{
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() = "g I";
    g.School = "School of the Kings";
    KingInfo(&g);
    King Henry;
    Henry.MyName() = "Henry II";
    KingInfo(&Henry);
    return 0;
}

Result


Related Tutorials