Re: beginner's question on static_cast and const_cast
<subramanian100in@yahoo.com> wrote in message
news:1195023595.896046.232950@k35g2000prh.googlegroups.com...
when are the use of static_cast and const_cast essential ?
Stroustrup, in his book TC++PL(3rd edition) in page number 139
(in Section 6.5 Advice - [4]), has advised
"Avoid explicit type conversion(casts)"
Given this, why do we have static_cast and const_cast
provided by the language ?
I use a library written by someone else (I don't have the code to it, just
an interface). Originally he did not write the function calls constant
correct, so would have things like:
void drawtext( char* Text, int x, int y );
Now, I'm using std::strings To use this function with my std::strings poses
a problem, as a string.c_str() returns a const char*, and you can not call a
function expecting a non constant pointer with a constant pointer. I
verified with the developer that the function did not change the string, and
so I could do this:
drawtext( const_cast<const char*>( MyString.c_str() ), x, y )
a bit ugly but it does the trick. It throws away the constantness. Usually
this would be used when interfacing with C functions or C++ functions that
are not constant correct. This would do the same thing the C style cast of:
drawtext( (const char*)MyString.c_str(), x, y )
would do. But one of the advantages of making so verbose is we want to get
rid of them. I talked to the developer and he went through and made the
functions constant correct which allowed me to use:
drawtext( MyString.c_str(), x, y )
There are reasons for static cast also, sometimes to just make the compiler
shut up about warnings without having to disable them, sometimes to cast
variables explicitly.
static_cast is not really as dangerous as reinterpret_cast though. Unless
you know what you are doing and think about all the consenquences
reinterpret_cast can get you in deep water. I find it useful, however, when
extracting binary data from some data.