C++ new cast forms

C++ offers four new cast forms (often called new-style or C++ style casts)

1. const_cast<T>(expr): used to case away the constness of objects. It is the only C++ style cast than can do this.

2. dynamic_cast<T>(expr): used to perform “safe downcasting”, i.e., to determine whether an object is of a particular type in an inheritance hierarchy. It is the only cast that cannot be performed using the old-style syntax. It is also the only case that may have a significant runtime cost.

3. reinterpret_cast<T>(expr): used for low-level casts that yield implementation-dependent (i.e unportable) results, e.g., casting a pointer to an int. Such casts should be rare outside love-level code.

4. static_cast<T>(expr): used to force implicit conversions (e.g. non-const object to const object, int to double, etc). It can also be used to perform the reverse of many such conversions (e.g. void* pointers to typed pointers, pointer-to-base to pointer-derived), though it cannot cast from const to non-const objects. (Only const_cast can do that)

Prefer C++ style casts to old-style casts because they are easier to see, and they are more specific about what they do

Tags: , ,

Leave a Reply