void DynamicCastFun()
{
    for( int n = 0; n < 3; ++n )
    {
        Base* base = CreateRandom();

        base->DoIt();

        // NOT TYPE SAFE: WE DON'T KNOW THE TYPE OF BASE
        // SO USE DYNAMIC CAST INSTEAD
        //Bar* bar = (Bar*)base;
        //bar->BarIt();

        Bar* bar = dynamic_cast<Bar*>(base);
        Foo* foo = dynamic_cast<Foo*>(base);
        if( bar )
            bar->BarIt();
        if( foo )
            foo->FooIt();

    }

    {
        Base* base = new Base();
        Foo* foo1 = dynamic_cast<Foo*>(base);
        if (foo1 == NULL)
        {
            cout << endl << "Dynamic Cast Failed. foo1 is NULL" << endl;
        }
        else
        {
            cout << endl << "Dynamic Cast Succeeded. foo1 is NOT NULL" << endl;
        }
    }
}
Пример #2
0
int main()
{
    /* regular cast */
//    float d=3.14159265;
//    int i = static_cast<int>(d);
//    cout << "i = " << i << endl << endl;




    for( int n = 0; n < 5; ++n )
    {
        Base* base = CreateRandom();

        base->DoIt();

        Bar* bar = static_cast<Bar*>(base);
        Foo* foo = static_cast<Foo*>(base);
        if( bar )
            bar->BarIt();
        if( foo )
            foo->FooIt();
        delete base;
        base = NULL;

        printf("-------------STATIC_CAST-------------- \n");
    }

    return 0;
}