Back: Exceptions
Forward: Variable Scoping in For Loops
 
FastBack: Variable Scoping in For Loops
Up: Changeable C++
FastForward: Compiler Quirks
Top: Autoconf, Automake, and Libtool
Contents: Table of Contents
Index: Index
About: About this document

16.2.3 Casts


C++ introduced a collection of named casting operators to replace the conventional C-style cast of the form (type) expr. The new casting operators are static_cast, reinterpret_cast, dynamic_cast and const_cast. They are reserved words.

These refined casting operators are vastly preferred over conventional C casts for C++ programming. In fact, even Stroustrup recommends that the older style of C casts be banished from programming projects where at all possible The C++ Programming Language, 3rd edition. Reasons for preferring the new named casting operators include:

  • They provide the programmer with a mechanism for more explicitly specifying the kind of type conversion. This assists the compiler in identifying incorrect conversions.
  • They are easier to locate in source code, due to their unique syntax: X_cast<type>(expr).

If your compiler does not support the new casting operators, you may have to continue to use C-style casts--and carefully! I have seen one project agree to use macros such as the one shown below to encourage those involved in the project to adopt the new operators. While the syntax does not match that of the genuine operators, these macros make it easy to later locate and alter the casts where they appear in source code.

 
#define static_cast(T,e) (T) e



This document was generated by Gary V. Vaughan on February, 8 2006 using texi2html