A comparison of the C++ casting operators

Hi community,

This post is about a feature that’s available in C++, which sometimes tends to confuse developers. I’m referring to casting operators. These operators complement the old C-style casting operator (provided for backwards compatibility), the C++ standard defines the following operators:

  • static_cast: It’s the most useful cast. It can be used to perform any implicit cast. When an implicit conversion loses some information, some compilers will produce warnings, and static_cast will eliminate these warnings. Making implicit conversion through static_cast is also useful to resolve ambiguity or to clarify the conversion presence. It also can be used to call a unary constructor, declared as explicit. It also can be used to cast up and down a class hierarchy, like dynamic_cast, except that no runtime checking is performed.
  • dynamic_cast: It’s used on polymorphic pointers or references to move up or down a class hierarchy. Note that dynamic_cast performs runtime-checks: if the object’s type is not the one expected, it will return NULL during a pointer-cast and throw a std::bad_cast exception during a reference-cast.
  • const_cast: It’s used to apply or remove const or volatile qualifier from a variable.
  • reinterpret_cast: It’s used to perform conversions between unrelated types, like conversion between unrelated pointers (like char* to void*) and references or conversion between an integer and a pointer.

Regards,

Angel

 

Leave a Reply

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