19.8.2.  reinterpret_cast

[ fromfile: types.xml id: reinterpretcast ]

reinterpret_cast is used for casts that are representation- or system-dependent. Examples are conversions between unrelated types such as int to pointer, or between unrelated pointer types such as int* to double*. It cannot cast away const.

reinterpret_casts are dangerous, generally not portable, and should be avoided.

Consider the following situation.

        Spam spam;
        Egg* eggP;
        eggP = reinterpret_cast<Egg*>(&spam);
        eggP->scramble();
      

reinterpret_cast takes some spam and gives us an Egg-shaped pointer, without any concern for type-compatibility. eggP is reinterpreting the bits of spam as if they were bits of egg. In some countries, this would be sacrilege!

What Is It Really Used For?

Sometimes, a C function returns a void* pointing to a type that is known to the developer. In such a case, a typecast from void* to the actual type is needed. If you are sure it is pointing to an Egg, reinterpret_cast<Egg*> is the appropriate cast to use. There is no compiler or runtime checking on such a cast.

For example, we use reinterpret_cast on a void* in the QMetaType example, Example 12.15.