A comparison of the C++ casting operators [C++ Reference]
Keywords: keywords,casting_comparison
Date: 2009-12-03T00:27:07-0800

[[A comparison of the C++ casting operators]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- cz
- de
- es
- fr
- it
- jp
- nl
- pl
- ro
- ru
- sk
- tr
- tw

## A comparison of the C++ casting operators

In addition to the C-style casting operator (provided for backwards compatibility) the C++ standard defines four additional casting operators:

- static_cast
- const_cast
- dynamic_cast
- reinterpret_cast

The purpose of these new casting operators is to provide better type checking. Their use is encouraged over the old C-style casting operator.

### Deficiencies of the old C-style cast

Two forms of the C-style cast are supported in C++:

      int age = (int) sqrt( foo / 3.25 );
      int age = int( sqrt(foo/3.25 ) );

However, using the same syntax for a variety of different casting operations can make the intent of the programmer unclear.

Furthermore, it can be difficult to find a specific type of cast in a large codebase.

Finally, the generality of the C-style cast can be overkill for situations where all that is needed is a simple conversion. The ability to select between several different casting operators of differing degrees of power can prevent programmers from inadvertently casting to an incorrect type.

### Different operators for different uses

The four casting operators in C++ can be used in different cases, where each is most appropriate:

static_cast is 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.

const_cast is used to apply or remove const or volatile qualifier from a variable.

dynamic_cast is 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.

reinterpret_cast is used to perform conversions between unrelated types, like conversion between unrelated pointers and references or conversion between an integer and a pointer.

Old-style cast may correspond to static_cast, reinterpret_cast or const_cast, or even a combination of them. This means that none of these casting operators is as powerful as old-style cast.

Related links: http://www.acm.org/crossroads/xrds3-1/ovp3-1.html

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •