Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created April 19, 2015 20:24
Show Gist options
  • Save dgodfrey206/33341ba2dfca3090462a to your computer and use it in GitHub Desktop.
Save dgodfrey206/33341ba2dfca3090462a to your computer and use it in GitHub Desktop.
More explicit type conversion
#include <new>
struct Parent { };
struct Child : Parent { };
struct Tag { };
int main()
{
const Child c;
Parent& p1 = const_cast<Parent&>(static_cast<Parent const&>(c));
Parent& p2 = (Parent&)c; // same as initializer for p1
const char buf[sizeof(Tag)]{};
new ((void*)buf) Tag();
Tag* tag1 = const_cast<Tag*>(reinterpret_cast<Tag const*>(buf));
Tag* tag2 = (Tag*)buf; // same as initializer for tag1
}
@dgodfrey206
Copy link
Author

The different C++ casts a C style cast will go through:

const_cast
static_cast
static_cast followed by const_cast
reinterpret_cast
reinterpret_cast followed by const_cast

It looks for the first viable cast for the conversion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment