Software & Finance





Visual C++ - reinterpret_cast





We use reinterpret_cast to convert from one data type to different data type which are mainly used for storing and retrieving. For example, converting a pointer object to a long value is called reinterpret_cast.

A commonly used example in MFC would be a CListCtrl consisting of many items and each item needs to be associated with a class pointer to store its properties, then we use CListCtrl::SetItemData and CListCtrl::GetItemData. Note that this function takes the DWORD as argument. We can pass a class member pointer as DWORD by converting using reinterpret_cast.

In this example, we are converting the pointer objects p1, p2, p3 to unsigned long values lValue1, lValue2, lValue3. And we are converting back the unsigned long value to Shape* pointer objects s1, s2, s3. Then we are checking whether s1 == p1 && s2 == p2 && s3 == p3.


Source Code


 

class Shape

{

public:

    Shape()

    {

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

    }

 

    virtual void draw() = 0;

};

 

class Rect1 : public Shape

{

    int l,b;

 

public:

    Rect1()

    {

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

    }

 

    virtual void draw() {}

};

 

class Circle : public Shape

{

    int r;

public:

    Circle()

    {

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

    }

 

    virtual void draw() {}

};

 

class Square : public Shape

{

    int a;

public:

    Square()

    {

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

    }

 

    virtual void draw() {}

};

 

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

{

 

    Shape *p1 = static_cast (new Rect1());

    Shape *p2 = static_cast (new Circle());

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

 

    unsigned long lValue1 = reinterpret_cast(p1); // casting to unsigned long

    unsigned long lValue2 = reinterpret_cast(p2); // casting to unsigned long

    unsigned long lValue3 = reinterpret_cast(p3); // casting to unsigned long

 

    Shape *s1 = reinterpret_cast(lValue1); // casting back to Shape*

    Shape *s2 = reinterpret_cast(lValue2); // casting back to Shape*

    Shape *s3 = reinterpret_cast(lValue3); // casting back to Shape*

 

    if( s1 == p1 &&

        s2 == p2 &&

        s3 == p3)

    {

        std::cout << "reinterpret_cast is Successfull\n\n";

    }

    return 0;

}

 

Output


reinterpret_cast is Successfull