Software & Finance





Visual C++ - static_cast





In this example, Shape is the base class. 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.



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 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 Square(); // Implict cast

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

    return 0;

}

 

 

 

Output


Shape
Rectangle

Shape
Square

Shape
Square