Possible Duplicate:
What is the difference between (type)value and type(value)?
I am mainly a C# developer and so do a lot of explicit casting using syntax like: (type)variable, with (int)100.0004d as an example. As such, when writing code in C++, I often use the same syntax. However, I have seen (and even used) code in other cases where the same cast is achieved using the syntax type(variable) with int(100.0004) as an example.
I was just curious as to what the difference between the two methods were and whether there were any implications in using one over the other.
Example:
double someDouble = 100.00456;
// Cast the double using the (type)variable syntax
int firstCastValue = (int)someDouble;
// Cast the double using the type(variable) syntax
int secondCastValue = int(someDouble);
The two are exactly the same, and this is true for any type.
Personally, I would avoid the first form,
(T)x, in favour of an explicit static cast:This expresses that you want to convert
xto the typeT.The second form is rather more evocative of a constructor call, and that’s sometimes preferable:
To repeat, both forms are entirely equivalent, and it’s a matter of taste which you prefer. I would use static cast for “converting” and constructor-syntax for “constructing”, if that makes any sense.