(C++) Cast
February 28, 2017 ยท View on GitHub
A cast is used to convert one data type to another.
There are four keywords for the different types of casts:
- static_cast: to cast related types, for example int to double
- dynamic_cast: to cast between types in an inheritance hierarchy, for example from the base class ChessPiece to its derived class Pawn
- const_cast
- reinterpret_cast
It is also possible to cast smart pointers:
- static_pointer_cast
- dynamic_pointer_cast
- const_pointer_cast
- shared_static_cast (deprecated [6])
- shared_dynamic_cast (deprecated [6])
- shared_polymorphic_cast (deprecated [6])
- shared_polymorphic_downcast (deprecated [6])
Advice
- Avoid casts [4,7]
- Don't use C-style casts [1-2,5,9], but use one of the four C++ casting keywords instead [1-3,5,8,9].
References
- 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'.
- 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'.
- 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'
- 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'
- 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.'
- Comment in shared_ptr.hpp (Boost version 1.49), line 536: 'shared_*_cast names are deprecated. Use *_pointer_cast instead.'
- 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)'
- 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'
- Gottschling, Peter. Discovering Modern C++: An Intensive Course for Scientists, Engineers, and Programmers. Addison-Wesley Professional, 2015. Chapter 6.5: 'Do not use C-style casts'