Modern C++
    Language Concepts
    Smart Pointers
    Memory Management
    Type Casting
    Trouble Shooting

C / C++ - Type Casting

Updated: 2022-02-05

C++-style Casting

  • static_cast performs no runtime checks. use it in cases like converting float to int, char to int, etc. Also used in CRTP.
  • dynamic_cast: used for handling polymorphism. Only used used in inheritence when casting from base class to derived class.
  • const_cast: can be used to remove or add const to a variable.
  • reinterpret_cast: used for reinterpreting bit patterns and is extremely low level, primarily for things like turning a raw data bit stream into actual data or storing data in the low bits of an aligned pointer.

C-style Casting

For example: (int)3.5

A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast. More powerful as it combines all of const_cast, static_cast and reinterpret_cast, but it's also unsafe.