liveBook · Manning

Reinterpret_cast

As explained in 100 C++ Mistakes and How to Avoid Them

reinterpret_cast is a C++ cast expression that reinterprets the representation of an object or pointer as another type without performing a normal value conversion.

reinterpret_cast tells the compiler to ignore the pointed-to data type and pretend it has another type. Use it very sparingly: it communicates intent, but accepts responsibility for the result. section 5.6

A practical cast-maintenance rule:

  • Prefer better-designed code that eliminates casts when possible. section 5.6
  • Use reinterpret_cast when deliberately viewing binary numeric data through another representation. section 5.6
  • Choose const_cast for constness, static_cast for compatible conversions, and dynamic_cast for checked polymorphic downcasts. section 5.6

Viewing an integer as bytes

A pointer to an integer can be reinterpreted as a char pointer, allowing its individual bytes to be read. The explicit cast exposes that representation-level intent instead of hiding it inside a C-style cast.

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Defines the cast’s pretending model and contrasts its responsibility with const_cast, static_cast, and dynamic_cast.
Examples
Demonstrates reading an integer’s bytes through a reinterpret_cast<char*> expression.
What you can do after
Apply it via a C++ cast expression when representation access is necessary and its risks are understood.
How it connects
Connects reinterpret_cast to C-style casts, const_cast, static_cast, and dynamic_cast.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.