I understand that a static_cast
is a cast from one type to another that (intuitively) is a cast that could under some circumstance succeed and be meaningful in the absence of a dangerous cast. Meanwhile, a reinterpret_cast
is a cast that represents an unsafe conversion that might reinterpret the bits of one value as the bits of another value.
Can someone describe a scenario when the code will compile, cast and static_cast
will cause no issue, but with reinterpret_cast
there will be an issue?
static_cast can't throw exception since static_cast is not runtime cast, if some cannot be casted, code will not compiles. But if it compiles and cast is bad - result is undefined.
The static_cast operator converts a null pointer value to the null pointer value of the destination type. Any expression can be explicitly converted to type void by the static_cast operator. The destination void type can optionally include the const , volatile , or __unaligned attribute.
Purpose for using reinterpret_cast It is used when we want to work with bits. If we use this type of cast then it becomes a non-portable product. So, it is suggested not to use this concept unless required. It is only used to typecast any pointer to its original type.
Static casts are only available in C++.
This will do it:
#include <iostream> using namespace std; struct C{int n;}; struct A{int n;}; struct B : A, C{}; int main() { B b; B* pb = &b; cout << static_cast<C*>(pb) << "\n"; cout << reinterpret_cast<C*>(pb); }
Note the differences in the two addresses.
I've built some multiple inheritance here, and have put an explicit member in the base classes, in order to circumvent possible optimisation of empty base classes to size zero.
See https://ideone.com/QLvBku
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With