Possible Duplicate:
When should static_cast, dynamic_cast and reinterpret_cast be used?
I’m using c function in c++, where a structure passed as a void type argument in c is directly stored that same structure type.
eg in C.
void getdata(void *data){
Testitem *ti=data;//Testitem is of struct type.
}
to do the same in c++ i use static_cast:
void foo::getdata(void *data){
Testitem *ti = static_cast<Testitem*>(data);
}
and when i use reinterpret_cast it does the same job, casting the struct
when i use Testitem *it=(Testitem *)data;
this does the same thing too.
But how is the structure gets affected by using the three of them.
A
static_castis a cast from one type to another that (intuitively) is a cast that could under some circumstance succeed and be meaningful in the absence of a dangerous cast. For example, you canstatic_castavoid*to anint*, since thevoid*might actually point at anint*, or anintto achar, since such a conversion is meaningful. However, you cannotstatic_castanint*to adouble*, since this conversion only makes sense if theint*has somehow been mangled to point at adouble*.A
reinterpret_castis a cast that represents an unsafe conversion that might reinterpret the bits of one value as the bits of another value. For example, casting anint*to adouble*is legal with areinterpret_cast, though the result is unspecified. Similarly, casting anintto avoid*is perfectly legal withreinterpret_cast, though it’s unsafe.Neither
static_castnorreinterpret_castcan removeconstfrom something. You cannot cast aconst int*to anint*using either of these casts. For this, you would use aconst_cast.A C-style cast of the form
(T)is defined as trying to do astatic_castif possible, falling back on areinterpret_castif that doesn’t work. It also will apply aconst_castif it absolutely must.In general, you should always prefer
static_castfor casting that should be safe. If you accidentally try doing a cast that isn’t well-defined, then the compiler will report an error. Only usereinterpret_castif what you’re doing really is changing the interpretation of some bits in the machine, and only use a C-style cast if you’re willing to risk doing areinterpret_cast. In your case, you should use thestatic_cast, since the downcast from thevoid*is well-defined in some circumstances.