reinterpret_cast Casting Operator Explained With Simple Example

This is one of the most complex and dangerous casting operators available in C++. The “reinterpret_cast” operator can convert any type of variable to fundamentally different type. This cast operator can convert an integer to a pointer and so on. This cast operator can also convert variable into totally incompatible type too.

Normal syntax to do reinterpret_cast is as follows:

reinterpret_cast <target-type> (expr)

target-type is the target of the cast whereas expr is being cast into the new target-type.

Important Points

  • This is one of the most complex and dangerous casting operators available in C++.
  • It can be used to cast any variable into incompatible type too.
  • It doesn’t perform any compile time (mostly) or run time checks for conversion viability.
  • This casting operator mainly used when programmer needs to work with bits.
  • Programs using this type casting operators are mostly not portable because of the byte order (little/big endian).
  • Since, reinterpret_cast doesn’t change the fundamental memory layout. Hence, casting it back to original type will yield the original pointer and nothing is lost in the process.

Let’s have a look at the sample program to understand reinterpret_cast operator functionality.

template <class T>
class NUM
{
    public:
        void demo ()
        {
            cout << "Inside NUM" << endl;
        }
};

int main ()
{
    int i = 70;
    int *p = reinterpret_cast <int *> (i);
    cout << "Initial value: " << i << " converted address: " << p << endl;

    /* Converting to random pointer and then back but value will be retained*/
    int *a = &i;
    NUM<int> *b = reinterpret_cast <NUM <int > *> (a);
    int *c = reinterpret_cast <int *> (b);
    cout << "Initial value: " << *a << " Coming back value: " << *c << endl;
}

Let’s analyze the output of above program.

Initial value: 70 converted address: 0x46
Initial value: 70 Coming back value: 70

Leave a Reply

Your email address will not be published. Required fields are marked *