Originally Posted by
Fordy
static_cast is a pretty safe little cast for converting things like ints to doubles etc...casts that wont cause any hassle
const_cast casts away the const quality of a variable and is handy in some tight circumstances when you know what you are doing
reinterpret_cast is the cast you use when you are doing something potentially dangerous & out of the ordinary that you are forced to do like casting a pointer to a differnt pointer or (more likely for winapi) casting an intergal to a function pointer (IE LONG to a WNDPROC)
Perhaps I can elaborate a little:
const_cast is used to convert from a pointer/reference to a constant type to a pointer/reference to the same type but without the const modifier
Here's how it'd look if const_cast wasn't a keyword:
Code:
template<typename T>
T* const_cast( const T* ptr)
{
return (T*)ptr; //C-style cast
}
//The same for references
Const cast might result in undefined behaviour.
Const cast must be used on pointer/reference types:
Code:
const int i = 0;
const_cast<int>(i) = 23; //Compile error
const_cast<int&>(i) = 23; //Legal, but undefined
*(const_cast<int*>(&i)) = 23; //Legal, but undefined
static_cast is used to convert between:
- Numerical types
- Pointers/references within the same class hierarchy without any run-time checks. If used so, it's a dynamic_cast that always succeed.
Code:
struct A { };
struct B : A { };
struct C { };
int main()
{
A* a;
B* b;
C* c;
b = a; //Compiler error
b = static_cast<B*>(a); //Can be dangerous
c = b; //Complier error
c = static_cast<C*>(b); //Compiler error -- C is unrelated to B
}
reinterpret_cast converts between totally unrelated types, for example between long and int*. It can also perform the conversion above, where static_cast will fail.
Hope that helps, distingushing between these cast are not always trivial.