What are the differences between
int a; // a gets some value double pi = static_cast<double>(a)/3;
and
int a; // a gets some value double pi = double(a)/3;
Have you ever seen the latter? It seems to me I saw it in some snippet written by Stroustrup but I can't find the reference.
static_cast is used to convert from pointer to base class to pointer to derived class, or between native types, such as enum to int or float to int. The user of static_cast must make sure that the conversion is safe. The C-style cast does not perform any check, either at compile or at run time.
Static casting is done by the compiler: it treats the result as the target type, no matter what. You do this when you're absolutely sure about the argument being of the target type. Dynamic casting is done at runtime, and thus requires runtime type information.
Static casts are only available in C++. Static casts can be used to convert one type into another, but should not be used for to cast away const-ness or to cast between non-pointer and pointer types.
The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.
Someone may have thought they were constructing rather than casting. Consider:
some_fun(std::string("Hello"));
Many people think they're calling a constructor there when in fact they're doing a C-style cast. It just so happens that casting will look at constructors of the target type among the long list of other things it looks at and so here it eventually ends up invoking the constructor.
Functional notation casts have all the same weaknesses of the other kind of C cast:
Besides all that though, you're performing exactly the same operation in both cases.
The latter is referred to as the functional notation of explicit casting where you explicitly say a
should be treated as a double
. You can pretty much cast anything to any type using this technique.
The former is the preferred way to cast a type in C++. It does basic checking to see that the type you are casting to makes sense (child class pointer to a base class pointer, etc.). In addition, like in the example you show, you can perform implicit conversions. Technically the static_cast
in your example is explicit, but the result of the operation (the assignment) is implicit.
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