<Pe*******@gmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
Hi,
An example usage of static_cast is at
http://publib.boulder.ibm.com/infoce...tatic_cast.htm
But I don't understand why it is necessary to use
float d = static_cast<float>(j)/v;
Isn't
float d = float(j)/v;
enough?
It isn't strictly necessary. float d = float(j)/v works. But there are
several reasons why you should use the various *_cast operators
1) It makes clear exactly what you are doing. static_cast forces
implicit conversions (int to float for instance) which is why you use it in
your example. const_cast casts away constness. reinterpret_cast makes the
computer pretend that a variable of one type is actually of another type.
dynamic_cast is used for run-time type identification; it checks whether a
pointer to a base type is actually a pointer to the target derived type then
returns the cast pointer if it is or 0 if it is not. A plain C cast can
replace any of these except dynamic_cast, but it is helpful to you and
anyone who will have to maintain your code later to be specific about what
you are doing.
2) It is much easier, both for humans and computers, to search for
static_cast in code than to look through all the parentheses to try to
determine which are casts.
Joe Gottman