Download presentation
Presentation is loading. Please wait.
Published byOswald Edwards Modified over 6 years ago
1
c++ style casting At the beginning c++ supported two styles of casts:
(typename)expression typename(expression) Instead there are now four new casting operators: static_cast<type>(expression) const_cast<type>(expression) reinterpret_cast<type>(expression) dynamic_cast<type>(expression)
2
The 'static_cast operator
static_cast<type>(expression) Works where implicit conversion exists standard or user-defined conversion up-casts Safer that “old-style” casts e.g. won’t cast int* to float* Failure causes a compiler error No dynamic checking is done! int i = static_cast<int>(12.45);
3
The ‘const_cast'operator
const_cast<type>(expression) Is used to remove (or add) const-ness: void g(C * cp); void f(C const* cp) { g(const_cast<C *>(cp)); } Usually, you should design your variables/methods such that you won’t have to use const_cast. Failure causes compiler errors
4
‘reinterpret_cast'operator
reinterpret_cast<type>(expression) Is used to reinterpret byte patterns. double d(10.2); char* dBytes = reinterpret_cast<char *>(&d); Circumvents the type checking of c++. Very implementation-dependent. Rarely used. Very dangerous !
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.