Software & Finance





Visual C++ - dynamic_cast





By extending example in the previous section of static cast, Shape is the base class. Circle, Square, Rectangle are the 3 classes dervied from the base class Shape. static_cast can be used to resolve ambiguity arises because of implicit casting by explictly specifying the data type while casting.

1. The object p1 initialization uses the C Style casting
2. The object p2 initialization uses implicit casting
3. The object p3 initialization uses using static_cast.

All the 3 pointer objects p1, p2, p3 are converted back to Circle pointer using dynamic_cast. Actually only the pointer p2 is a pointer to Circle object. The outcome would p1 and p3 will get the NULL value and p2 will get the pointer to Circle Object. This casting requires RTTI (Run-Time Type Information) to be enabled.


Source Code


 

class Shape

{

public:

    Shape()

    {

    std::cout << "Shape\n";

    }

    virtual void draw() = 0; // pure virtual function

};

 

class Rect1 : public Shape

{

    int l,b;

public:

    Rect1()

    {

        std::cout << "Rectangle\n\n";

    }

 

    virtual void draw()

    {

        std::cout << "Drawing Rectangle\n\n";

    }

};

 

class Circle : public Shape

{

    int r;

 

public:

    Circle()

    {

        std::cout << "Circle\n\n";

    }

 

    virtual void draw()

    {

        std::cout << "Drawing Circle\n\n";

    }

};

 

class Square : public Shape

{

    int a;

public:

    Square()

    {

        std::cout << "Square\n\n";

    }

 

    virtual void draw()

    {

        std::cout << "Drawing Square\n\n";

    }

};

 

int _tmain(int argc, _TCHAR* argv[])

{

 

    Shape *p1 = (Shape*) (new Rect1()); // C Style Casting equal to static_cast

    Shape *p2 = new Circle(); // Implict cast

    Shape *p3 = static_cast (new Square()); // static_cast

 

    Circle* c1 = dynamic_cast(p1);

    Circle* c2 = dynamic_cast(p2);

    Circle* c3 = dynamic_cast(p3);

 

    if(c1 == NULL)

        std::cout << "c1 is not a pointer to Circle\n";

    else

        std::cout << "c1 is a pointer to Circle\n";

 

    if(c2 == NULL)

        std::cout << "c2 is not a pointer to Circle\n";

    else

        std::cout << "c2 is a pointer to Circle\n";

 

    if(c3 == NULL)

        std::cout << "c3 is not a pointer to Circle\n\n";

    else

        std::cout << "c3 is a pointer to Circle\n\n";

 

    return 0;

}

 

 

Output


Shape
Rectangle

Shape
Circle

Shape
Square

c1 is not a pointer to Circle
c2 is a pointer to Circle
c3 is not a pointer to Circle