Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Cast

 

A cast is used to convert one data type to another. Avoid casts [4,7]. Don't use C-style casts [1-2,5], but use one of the four C++ casting keywords instead [1-3,5,8].

 

There are four keywords for the different types of casts:

  1. static_cast: to cast related types, for example int to double
  2. dynamic_cast: to cast between types in an inheritance hierarchy, for example from the base class ChessPiece to its derived class Pawn
  3. const_cast
  4. reinterpret_cast

 

It is also possible to cast smart pointers:

 

 

 

 

 

References

 

  1. Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4 6.5.5: 'When explicit type conversion is necessary, prefer the more specific cast operators to the C-style cast'.
  2. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Item 95: 'Don't use C-style casts'.
  3. John Lakos. Large-Scale C++ Software Design. 1996. ISBN: 0-201-63362-0. Section D.4. Guidelines, chapter 9, page 823: 'Consider avoiding 'cast' operators, especially to fundumental integral types; instead, make the conversion explicit'
  4. Joint Strike Fighter Air Vehicle C++ Coding Standards for the System Development and Demonstration Program. Document Number 2RDU00001 Rev C. December 2005. AV Rule 183: 'Every possible measure should be taken to avoid type casting'
  5. Joint Strike Fighter Air Vehicle C++ Coding Standards for the System Development and Demonstration Program. Document Number 2RDU00001 Rev C. December 2005. AV Rule 185: 'C++ style casts (const_cast, reinterpret_cast, and static_cast) shall be used instead of the traditional C-style casts.'
  6. Comment in shared_ptr.hpp (Boost version 1.49), line 536: 'shared_*_cast names are deprecated. Use *_pointer_cast instead.'
  7. Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 11.6. Advice. page 303: '[12] Avoid explicit type conversions (casts)'
  8. Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 11.6. Advice. page 303: '[13] When explicit type conversion is necessary, prefer a named cast'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict