Presentation is loading. Please wait.

Presentation is loading. Please wait.

c++ style casting At the beginning c++ supported two styles of casts:

Similar presentations


Presentation on theme: "c++ style casting At the beginning c++ supported two styles of casts:"— Presentation transcript:

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 !


Download ppt "c++ style casting At the beginning c++ supported two styles of casts:"

Similar presentations


Ads by Google