<sh********@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
Hi All,
Do people frequently use static_cast, const_cast etc in industry?.. I
only saw them in books, and never in real code..
Shrish
To be honest, I still have trouble forcing myself to use static_cast instead
of the old C-style cast, since I've been doing it the old way for so long.
But if a cast is neccessary, and the proper cast for the situation is
static_cast, then your only other choice is a C-style cast, right? And
that's a worse option, not a better one.
So the question is, where is static_cast needed?
Well, one place I need it often is to force my mathematical calculations to
use a specific numeric type. For example, if I'm dividing two integers, but
I need a floating-point result, I need to either use a cast, or else assign
one of those values to a temporary float (or double) variable. A cast is
easier. (If I don't do this, then the division is integer division, which
loses the real portion of the answer!)
The other place I use it often is in callback functions (esp. when dealing
with the Windows API). In those functions, there is often a void* pointer
that is passed to my function, which I set up however I see fit when I
specify the callback to the OS. Usually I set the pointer to the value of
"this", so that the object who needs to be "called back" is identified. The
callback function then uses a static_cast to turn that void* into a pointer
to a pointer to my class type, so that I can then call a member function of
the object itself to do the actual work of the callback. This mechanism
allows me to make callbacks into C++ objects, using a "generic" C-style API,
which has no knowledge of my C++ class types.
There are obviously other cases where static_cast is used, but these are my
most common uses of it.
-Howard