tags:

views:

579

answers:

3

Could somebody please elaborate on the differences?

A: 

(int) foo compares most to c++ reinterpret_cast<int>, i.e. no checks on the validity of the cast.

Fredrik Jansson
http://www.velocityreviews.com/forums/t280611-reinterpretcastltgt-v-staticcastltgt.html expains the difference between static_cast and reinterpret_cast
Fredrik Jansson
No, it compares to a combination of all the C++ casts. It'll perform the first type of cast that's valid.
jalf
True, except for dynamic_cast is not included.
Fredrik Jansson
Are you trying to say that the problem with (int)foo is that it probably falls through to reinterpret_cast<foo> most times? So you don't actually get the benefit of static type checking.
bmatthews68
This answer is wrong. reinterpret_cast can, as other c++ casts, do only very little compared to a c-style cast.
Johannes Schaub - litb
+8  A: 

The difference is that (int)foo can mean half a dozen different things. It might be a static_cast (convert between statically known types), it might be a const_cast (adding or removing const-ness), or it might be a reinterpret_cast (converting between pointer types)

The compiler tries each of them until it finds one that works. Which means that it may not always pick the one you expect, so it can become a subtle source of bugs.

Further, static_cast is a lot easier to search for or do search/replace on.

jalf
Thank you for the clear and concise answer. +1.
Evan Fosmark
C-style casts can't do "safe" downcasting like dynamic_cast, only "unsafe" downcasting like static_cast.
bk1e
Also, I put "safe" and "unsafe" in quotes because nothing in C++ is truly safe.
bk1e
" (int)foo ... might be a dynamic_cast (downcasting to derived class)"Not true. (int)foo will never turn into a dynamic cast.
Suma
+4  A: 

Look at what Stroustrup has to say about that.

Christoph