Posted By: Anonymous
In traditional C you can do:
int i = 48; char c = (char)i; //Now c holds the value of 48. //(Of course if i > 255 then c will not hold the same value as i).
Which of the c++ casting methods (static_cast, reinterpret_cast) is suited for getting this job done?
You can implicitly convert between numerical types, even when that loses precision:
char c = i;
However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use
static_cast for the conversion.
Of the other casts:
dynamic_castonly works for pointers or references to polymorphic class types;
const_castcan’t change types, only
reinterpret_castis for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won’t do numeric conversions.
- C-style and function-style casts do whatever combination of
reinterpret_castis needed to get the job done.