C++ Explicit type conversions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

An expression can be explicitly converted or cast to type T using dynamic_cast<T>, static_cast<T>, reinterpret_cast<T>, or const_cast<T>, depending on what type of cast is intended.

C++ also supports function-style cast notation, T(expr), and C-style cast notation, (T)expr.

Syntax

  • simple-type-specifier ( )
  • simple-type-specifier ( expression-list )
  • simple-type-specifier braced-init-list
  • typename-specifier ( )
  • typename-specifier ( expression-list )
  • typename-specifier braced-init-list
  • dynamic_cast < type-id > ( expression )
  • static_cast < type-id > ( expression )
  • reinterpret_cast < type-id > ( expression )
  • const_cast < type-id > ( expression )
  • ( type-id ) cast-expression

Remarks

All six cast notations have one thing in common:

  • Casting to an lvalue reference type, as in dynamic_cast<Derived&>(base), yields an lvalue. Therefore, when you want to do something with the same object but treat it as a different type, you would cast to an lvalue reference type.
  • Casting to an rvalue reference type, as in static_cast<string&&>(s), yields an rvalue.
  • Casting to a non-reference type, as in (int)x, yields a prvalue, which may be thought of as a copy of the value being cast, but with a different type from the original.

The reinterpret_cast keyword is responsible for performing two different kinds of "unsafe" conversions:

The static_cast keyword can perform a variety of different conversions:

  • Base to derived conversions

  • Any conversion that can be done by a direct initialization, including both implicit conversions and conversions that call an explicit constructor or conversion function. See here and here for more details.

  • To void, which discards the value of the expression.

    // on some compilers, suppresses warning about x being unused
    static_cast<void>(x);
    
  • Between arithmetic and enumeration types, and between different enumeration types. See enum conversions

  • From pointer to member of derived class, to pointer to member of base class. The types pointed to must match. See derived to base conversion for pointers to members

  • void* to T*.

C++11


Got any C++ Question?