Software & Finance





Visual C++ - Casting Styles





In C++, There are 4 styles of casting available.



static_cast


In C++, we use static_cast in place of C style casting. It can be used to convert any variable, can be a pointer, if we are sure that the conversion would be successfull. For example, casting from char* to unsigned char* is an example for static_cast.

char buf[128];
char *p = buf;
unsigned char *up = static_cast (p);

dynamic_cast


We need RTTI (Run-Time Type Information) support to this kind of casting. We use dynamic_cast when we are not sure whether the conversion is going to be successfull or not. A typical example would be converting from a base class pointer to derived class pointer. Many classed can be derived from a single base class.

Dervied class pointer to base class pointer conversion would always to successfull and so we can apply static_cast here.

reinterpret_cast


We use reinterpret_cast to convert from one data type to different data type which are mainly used for storing and retrieving. For example, converting a pointer object to a long value is called reinterpret_cast. Usually we use reinterpret_cast for call back function or function pointers to specify the arguments. Lets say the call back function takes LPARAM as an argument. We can pass any structure or class pointer by converting to LPARAM while calling the function. With in the call back function, we can do another reinterpret_cast for converting from LPARAM to corresponding structure or class pointer.


const_cast


const_cast is used to cast const objects to non const and non const object to const objects. However it deficits the purpose of using const variable, it is used in some rare cases where we must convert const to non const objects.