RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


There's More to Typecasting than C++ Cast Operators : Page 2

Knowing exactly which typecasting operation is required for a given task and familiarity with the little known techniques that automate type conversions is essential--even in state-of-the-art C++ projects.


Presenting the Problem
When I introduced C++ cast operators more than six years ago, I truly wanted to believe that they were the right thing to use in through and through C++ programs. And yet, numerous questions from readers and my own experience have made me question C++ cast operators. This doesn't mean that you should throw C++ cast operators out of the window. However, you should familiarize yourself with alternative cast techniques to produce better code.

Cast Away
In spite of the frowns with which C-style cast is often greeted, it's a powerful and smart tool. The syntax is simple: enclose the target type in a pair of parentheses and place the argument after the parentheses. The following example casts a function pointerto long using C-style cast:

void myfunc(bool) 
void (*pf) (bool) = myfunc;
long long val= (long long) myfunc;

Replacing C-style with C++ cast operators will put you in a dilemma—should you use static_cast or reinterpret_cast? The "recommended" solution is to start with static_castand see if it works:

long long val= static_cast<long long> (myfunc);

Notice how verbose and ugly this statement is compared to the elegance and compactness of C-style cast. But it get worse—this code doesn't even compile. You need to use reinterpret_cast here, not static_cast:

long long val= 
 reinterpret_cast<long long> (myfunc); //ugly but works

No wonder why many C++ programmers give up static_cast entirely and stick to reinterpret_casteven when it's wrong.

Unlike C++ cast operators, a single C-style cast expression can perform two different conversions at once as shown in the following example:

void func(unsigned char * data);//doesn't modify data
const char txt[]="ABC";
func ((unsigned char*) txt);//remove const, add unsigned

C++ pundits didn't like this because the code is purportedly not explicit enough. However, using C++ cast notation makes the code extremely obfuscated, which doesn't exactly make your code clearer or safer:

func (reinterpret_cast<unsigned char *>
(const_cast<char *>(txt)));//remove const, add unsigned

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date