THE POST BELOW IS MORE THAN 5 YEARS OLD. RELATED SUPPORT INFORMATION MIGHT BE OUTDATED OR DEPRECATED
On 15/09/2008 at 02:41, xxxxxxxx wrote:
As I read it, the C style cast (type)var will do whatever it takes to promote var to the type, sometimes truncating values or making wild guesses (or compiler errors/warnings). This can lead to undesirable effects if not done carefully.
The four C++ style casts have different purposes:
const_cast: override const or volatile in a cast of the same type.
static_cast: casts on polymorphic types. that is, to cast a base class pointer to a derived class pointer.
dynamic_cast: cast with checks. this is a more stringent cast check on whether or not the type can be cast to a base or derived class or type.
reinterpret_class: no, don't use it!! It is used to cast completely incompatible types from one to the other (such as an int into a pointer or vice versa).
For the most part, if you are just casting to resolve a derived class from a base class, use static_cast. If you are converting more basic types (int, long, float, etc.), the C style may work depending upon the type of response you expect. It is rather easy to understand that casting a floating point value into an integral value is going to lose the decimal part no matter how you do it. Best to control it with floor(), ceil(), so that it is more constricted in these cases.
The key thing is to understand the ramifications of a cast of any style. void* casts are basically dynamic_cast but work as well using (type)var because your are assigning no-type to some-type as expected. Just make sure that the data is what you think.