Lecture overview -- Keyboard shortcut: 'u'  Previous page: Implicit type conversions -- Keyboard shortcut: 'p'  Next page: Function Overloading -- Keyboard shortcut: 'n'  Lecture notes - all slides and notes together  slide -- Keyboard shortcut: 't'  Help page about these notes  Alphabetic index  Course home  Lecture 2 - Page 24 : 42
Notes about C++
Basic facilities
Explicit type conversion

C++ supports a number of different kinds of type castings

Use of these cast operations makes it easier for the programmer to spot the more dangerous type conversions

  • The C++ Programming Language: Page 130-131, 407-408 (dynamic casts), 819
 

  • static_cast<T>(expr)

    • Casting between related types

    • Can activate built-in or user-defined type conversion, conversion operators, and implicit/explicit constructors.

    • Cannot cast away const

Probably the most frequently used, see item 2 of More Effective C++

  • reinterpret_cast<T>(expr)

    • Casting between unrelated types, potentially unsafe

    • Can cast between pointer types, and between integer and pointer types.

    • ... provides a value of new type that has the same bit pattern as its argument

  • dynamic_cast<T>(expr)

    • Primarily for downcasting or crosscasting of a pointer to an object (of polymorphic type)

    • For a pointer p, dynamic_cast<T>(p) can be seen as the question: 'Is the object pointed to by p of type T ?'.

  • const_cast<T>(expr)

    • Add or remove const (or volatile) qualifier to a type