Using New Cast Operators for Safe Typecasting
By Danny Kalev, C++ Pro

Although the C-style casting notation of the following form:

void *p=&x;
int n=(int)p; //cast pointer to int

is still widely used, it has several potential dangers. First, it performs different operations in different contexts. For example, it may perform a safe int to double promotion but it can also perform inherently dangerous operations such as casting a pointer to int (as in the example above). The programmer can't always tell from the source code if the cast is relatively safe or inherently dangerous. Worse yet, C-style cast may perform multiple operations at once. In the following example, not only does it cast a 'char *' to 'unsigned char *', it also removes the const qualifier at the same time:

const char *msg="don't touch!";
unsigned char *p=(unsigned char*) msg; // intentional?

Again, one cannot tell whether this was the programmer's intention or an unfortunate bug.



The ailments of C-style cast have been known for years. C++ offers a superior alternative to it in the form of new cast operators that document the programmer's intent more clearly while preserving the compiler's ability to catch potential bugs.



Use new cast operators. Originally, the C++ standardization committee wanted to deprecate C-style cast. However, because C-style cast is widely used in legacy code and because many C++ compilers serve as C compilers too, the committee decided not to do so. However, C++ programmers are encouraged to use the new cast operators instead. In the following sections I will present these operators and show how they improve the type-safety and readability of your code.

  
Next: Using static_cast

Introduction
Using static_cast
Using const_cast

Return to Get Help with C/C++ Page

Return to Main Get Help Page


 




Find Out More

All DevX 10-Minute Solutions for C/C++

DevX Tip: What's a "Deprecated Feature?"

Why Must I Use a Cast to Convert from void*?

Const Correctness

DevX Tip: Use reinterpret_cast<> Operator for Unsafe, Non-portable Casts


TALK BACK
The new cast operators have been criticized for the their verbosity. Some users claim that the existence of three different operators is superfluous and causes more confusion. What is your stance? Which notation do you prefer, traditional C-style cast or the new C++ cast operators?


Sponsored Links