Search code examples
c++casting

In C++, what are the differences between static_cast<double>(a) and double(a)?


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.


Solution

  • 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:

    • Can inadvertently cast away constness
    • Can silently turn into a reinterpret cast
    • Are hard to differentiate with grepping tools.

    Besides all that though, you're performing exactly the same operation in both cases.