Sunday, 11 November 2012

Program illustrating Dynamic Cast in C++

//Program illustrates how dynamic_cast keyword in C++ is used

#include<iostream>
#include<typeinfo>
using namespace std;

class a
{
    public:
    virtual void show()=0;
};
class b : public a
{
    public:
    void show()
    {
        cout<<"\nshow() in class B\n";
    }
};
class c : public a
{
    public:
    void show()
    {
        cout<<"\nshow() in class C\n";
    }
};
class d : public a
{

   public:
   void show()
    {
        cout<<"\nshow() in class D\n";
    }
};
int main()
{
    int i,j;
    b b1,b2;
    c c1;
    d d1;
    a *a1[4]={&b1,&c1,&d1,&b2};

    for(i=0;i<4;i++)
    {
        b *b3=dynamic_cast<b *>(a1[i]);
        if(b3)
        {
            cout<<"\nFrom B\n" ;
            b3->show();
        }
        else
        {
            cout<<"\nNot From B\n";
            cout<<"a1["<<i+1<<"] is pointing to"<<typeid(*a1[i]).name()<<"\n";
            a1[i]->show();
        }

    }

    return 0;
}

Click here to download the C++ Program.

No comments:

Post a Comment