Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ type casting. When will static_cast succeed and reinterpret_cast will cause an issue?

Tags:

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?

like image 914
Narek Atayan Avatar asked Jun 30 '17 11:06

Narek Atayan


People also ask

Can static_cast fail?

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.

What happens when you perform a static_cast?

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.

When should I use Reinterpret_cast?

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.

Can I use static_cast in C?

Static casts are only available in C++.


1 Answers

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

like image 114
Bathsheba Avatar answered Nov 10 '22 00:11

Bathsheba