In article <ee300167.0401141842.2695de5e@posting.google.com >,
forums_mp@hotmail.com says...
[ ... ]
[color=blue]
> reinterpret_cast is ONLY for pointers, of the same constness. You can
> cast a char* to an unsigned char* or any other * with
> reinterpret_cast, but you can't cast off constness with reinterpret
> cast.[/color]
IIRC, reinterpret_cast can be used on references as well as pointers.
[color=blue]
> const_cast is to cast off constness. If you have a const char* and
> ABSOLUTELY MUST get rid of its constness and KNOW FOR A FACT that that
> operation is safe AND you can't just make a new copy of the buffer ...
> then const_cast is your tool.[/color]
const_cast can also be used to modify volatility.
[color=blue]
> static_cast is for casting a base class to a derived class. No
> runtime type checking is performed so this seems/is inherently
> dangerous, but sometimes if you are stuck with a bad design ...
> unavoidable. You can also cast an int to an enum using static cast,
> as well as a few other things.[/color]
You should almost never use static_cast to cast between different types
in the same hierarchy -- moving up the hierarchy can be done implicitly,
and down the hierarchy should normally use dynamic_cast. static_cast
should normally be used for things like floating->integer.
[color=blue]
> dynamic_cast is a "safe" way to cast a base class to a derived class,
> but it requires you to include type information in your build. if at
> runtime, if the cast can't be performed, then the cast returns 0,
> otherwise the cast succeeds and you continue your program.[/color]
That's how it works for pointers. For references, dynamic_cast succeeds
or throws and exception.
[color=blue]
> Along the same lines I have a question.
> Notwithstanding the C++ casts are limited in scope which in my view
> implies (no proof though) that they are safer than the C variant,
> whats the 'real' gain over the C cast? A question that seems to crop
> up with no reasonable answer on my part. I suspect in the grand
> scheme of things casting it's low level bit twiddling on both parts
> (C/C++)[/color]
Anything that tries to talk about "the 'real' gain" is almost certain to
be wrong. There are a number of improvements. dynamic_cast provides a
capability that a C-style cast simply doesn't provide at all.
const_cast provides a capability that a C-style cast could provide, but
is safer since it won't let you accidentally cast to some type that's
totally unrelated to the original type or something like that. From an
entirely different sort of viewpoint, it's essentially impossible to
grep for C-style casts, but trivial to do so for the new C++ casts.
--
Later,
Jerry.
The universe is a figment of its own imagination.