Home / C++ / C++ casts edit

const_cast : removes const (const char* s = "foo"; char* s2 = const_cast(s); )

static_cast : int → double, pointer → void* etc.

reinterpret_cast : "trust me" cast

dynamic_cast : only for polymorphic types (those that have virtual functions) and when rtti is enabled. Used to cast up&down inheritance hierarchy. Returns null if cast can't be done on a pointer. Throws exception if cast fails on reference type.

Unclear: when casting Foo* <-> void* should I use static_cast or reinterpret_cast ?

Google rules

Do not use C-style casts. Instead, use these C++-style casts when explicit type conversion is necessary.

  • Use brace initialization to convert arithmetic types (e.g. int64{x}). This is the safest approach because code will not compile if conversion can result in information loss. The syntax is also concise.
  • Use static_cast as the equivalent of a C-style cast that does value conversion, when you need to explicitly up-cast a pointer from a class to its superclass, or when you need to explicitly cast a pointer from a superclass to a subclass. In this last case, you must be sure your object is actually an instance of the subclass.
  • Use const_cast to remove the const qualifier (see const).
  • Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if you know what you are doing and you understand the aliasing issues.

Links:

Go to index of articles.

Share on