Pallav said:
HI
whats the cretiria on which i choose
1. reinterpret_cast<>()
2. static_cast<>()
There isn't a lot of choice, actually. If you need to use static_cast,
use static_cast. If you need to use reinterpret_cast, use
reinterpret_cast. Their use cases don't overlap. In some situations
the compiler lets you use do both but there's only one correct cast
(depending on the situation) and it is usually the static_cast
operator (or even a dynamic_cast).
A reinterpret_cast can be used to convert between different pointer/
reference types as well as between pointers and integers by
*reinterpreting* the bitpattern as a pointer to another type or
integer:
T* -> U* -> T* (where T and U have possibly nothing
T& -> U& -> T& to do with each other)
T* -> large_enough_int_type -> T*
One thing it can't do is removing const or volatile. Only const_cast
can do that. Anyhow, it's dangerous and should only be used with care.
It's important to keep §3.10/15 of the C++ standard in mind when you
use reinterpret_cast. You can look it up in one of the older C++0x
drafts that are still close to C++03: <
http://www.open-std.org/jtc1/
sc22/wg21/docs/papers/2005/n1804.pdf>. It's also important to keep in
mind that a conversion between base* and derived* might require a
pointer adjustment due to multiple inheritance. Therefore,
reinterpret_cast is not suited for these kinds of conversions. Use a
static_cast or dynamic_cast instead.
A static_cast with respect to scalar types can basically make implicit
conversions explicit as well as reverting most of them. For example:
derived* d1 = ...;
base* b = d1;
derived* d2 = static_cast<derived*>(b);
assert(d1==d2);
foo* x = ...;
void* y = x;
foo* z = static_cast<foo*>(y);
assert(x==z);
But these pointer casts don't involve any runtime checking. You, as a
programmer, have to be sure about the correct types. I guess that's
why this operator is called "static_cast" as opposed to
"dynamic_cast". Of course, a static_cast can also do other things:
struct A { A(int); };
struct B { explicit B(int); };
A w = 23; // OK (implicit conversion)
A x = static_cast<A>(23); // OK (explicit conversion)
B y = 23; // error! no implicit conversion
B z = static_cast<B>(23); // OK (explicit conversion)
int i = 3.14; // OK (implicit conversion)
int j = static_cast<int>(3.14) // OK (explicit conversion)
....and in the near future...
struct C { explicit operator bool() const; };
C c;
if (c) { // OK
bool b1 = c; // error!
bool b2 = true && c; // OK
bool b3 = static_cast<bool>(c); // OK
}
(in a boolean context explicit conversion operators are considered)
Check out your favorite C++ book on the cast operators. One could
write a whole chapter about what cast operators there are and what
they do exactly. You won't find any short explanation that covers all
the details...
Cheers!
SG