static_cast and reinterpret_cast

Started by
5 comments, last by peter86 21 years, 5 months ago
What´s the diffrence between static_cast and reinterpret_cast?
Advertisement
static_cast can perform checks and things at compile-time. reinterpret_cast is for non-standard casts that can''t be assured.
i think you'll find this link useful for many things

[edited by - petewood on October 31, 2002 5:22:20 PM]
actually looking at the cpp faq lite there isn''t anything in particular to answer your question... but it is useful

if you''re looking at casting something it''s probably likely you can get rid of it by some redesign.

sorry, can''t go into more detail, i''m a bit squiffy and going to bed.

peace
So how do I know when I should which?
quote:
From The C++ Programming Language
By Bjarne Stroustrup, Creator of C++
3rd Edition, page 130, section 6.2.7

Explicity Type conversion

The static_cast operator converts between related types such as one pointer type to another in the same class hierarchy, an integral type to an enumeration, or a floating-point type to an integral type. The reinterpret_cast handles conversions beween unrelated types such as an integer to a pointer or a pointer to an unrelated pointer type. This distinction allows the compiler to apply some minimal type checking for static_cast and makes it easier for a programmer to find the more dangerous conversion represented as reinterpret_casts. Some static_casts are portable, but few reinterpret_casts are. Hardlly any guarantees are made for reinterpret_cast, but generally it produces a value of a new type that has the same bit pattern as its argument. If the target has at least as many bits as the original value, we can reinterpret_cast the result back to its original type and use it. The result of a reinterpret_cast is guaranteed to be usable only if its result type is the exact type used to define the value involved.

daerid@gmail.com
reinterpret_cast is usually used for converting pointer types to other pointer types, or integral numbers to pointers and vice versa. static_cast is used primarily with converting among class pointer types, such as from base classes to derived class pointers. Basically, if it doesn''t compile, try the other one

This topic is closed to new replies.

Advertisement