4/23/08

the Differences Between static_cast and reinterpret_cast

The operators static_cast and reinterpret_cast are similar: they both convert an object to an object of a different type. However, they aren't interchangeable. Static_cast uses the type information available at compile time to perform the conversion, making the necessary adjustments between the source and target types. Thus, its operation is relatively safe. On the other hand, reinterpret_cast simply reinterprets the bit pattern of a given object without changing its binary representation. To show the difference between the two, let's look at the following example:
int n = 9;
double d = static_cast < double > (n);
In this example, we convert an int to a double. The binary representation of these types is very different. In order to convert the int 9 to a double, static_cast needs to properly pad the additional bytes of d. As expected, the result of the conversion is 9.0. Now let's see how reinterpret_cast behaves in this context:
int n = 9;
double d = reinterpret_cast< double & > (n);
This time the results are unpredictable. After the cast, d contains a garbage value rather than 9.0. This is because reinterpret_cast simply copied the bit pattern of n into d as is, without making the necessary adjustments. For this reason, you should use reinterpret_cast sparingly and judiciously.

2 comments:

Anonymous said...

But where do we actually use reinterpret_cast ?

Sumedh said...

reinterpret_cast is basically a bit manipulation casting.

Uses ex:
Let us say we are using receiving some object as buffer. we are not sure if what type of object that buffer may be holding. again directly assigning to a specific type of object may not be useful. We can use this reinterpret_cast to cast that buffer to some object type.

Ex. 2. if you are receiving some blob of object stored in databases or files which can be used to construct the objects we can use this.