When I try to use a static_cast to cast a double* to an int*, I get the following error:
invalid static_cast from type ‘double*’ to type ‘int*’
Here is the code:
#include <iostream> int main() { double* p = new double(2); int* r; r=static_cast<int*>(p); std::cout << *r << std::endl; }
I understand that there would be problems converting between a double and an int, but why is there a problem converting between a double* and an int*?
As we learnt in the generic types example, static_cast<> will fail if you try to cast an object to another unrelated class, while reinterpret_cast<> will always succeed by "cheating" the compiler to believe that the object is really that unrelated class.
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.
static_cast is actually an operator, not a function.
This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc.
You should use reinterpret_cast
for casting pointers, i.e.
r = reinterpret_cast<int*>(p);
unless you want take a int
-level look at a double
! You'll get some weird output and I don't think this is what you intended. If you want to cast the value pointed to by p
to an int
then,
*r = static_cast<int>(*p);
Also, r
is not allocated so you can do one of the following:
int *r = new int(0); *r = static_cast<int>(*p); std::cout << *r << std::endl;
Or
int r = 0; r = static_cast<int>(*p); std::cout << r << std::endl;
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