C++ Casting Operators Explained With Simple Example

Type casting is the method to convert variable (or expression) of a type to another type. Casting operators are special operators which are used to convert variable of one data type to another data type. Type casting can be done in two ways:

Implicit casting is being done automatically where values are copied to another compatible type. Eg: int to long int or float etc.

Explicit casting is done specifically by the programmer. In C++ there are four types of casting operator available.

dynamic_cast

This is one of the most important casting operators. The “dynamic_cast” performs a run-time type casting which also checks the type casting validity. If type casting is done to compatible type then it succeeds else it will throw “bad_cast” exception.

Normal syntax to do dynamic_cast is as follows:

dynamic_cast <target-type> (expr)

target-type and expr must be a pointer or reference.

For more information check dynamic_cast explanation.

const_cast

This is one of the most dangerous casting operators. The “const_cast” operator is used to remove the const or volatile property of a variable. The target-type and source-type must be of the same type here.

Normal syntax to do const_cast is as follows:

const_cast <target-type> (expr)

target-type and expr must be of same type pointer or reference.

For more information check const_cast explanation.

static_cast

This is the simplest type casting operator available in C++. The “static_cast” operator performs a normal cast. This casting operator is basically a substitute for normal casting operator. “static_cast” operator doesn’t do any runtime checks and hence programmer should consider whether casting is applicable or not.

Normal syntax to do static_cast is as follows:

static_cast <target-type> (expr)

target-type is the target of the cast whereas expr is being cast into the new target-type.

For more information check static_cast explanation.

reinterpret_cast

This is one of the most complex and dangerous casting operators available in C++. The “reinterpret_cast” operator can convert any type of variable to fundamentally different type. This cast operator can convert an integer to a pointer and so on. This cast operator can also convert variable into totally incompatible type too.

Normal syntax to do reinterpret_cast is as follows:

reinterpret_cast <target-type> (expr)

target-type is the target of the cast whereas expr is being cast into the new target-type.

For more information check reinterpret_cast explanation.

Leave a Reply

Your email address will not be published. Required fields are marked *