Skip to main content

11. Casting and Operator overloading

09/03/23

Casting

  • const_cast<newtype>(?) - Get rid of constness or volatileness
  • dynamic_cast<newtype>(?) - Safely cast a pointer or reference from base-class to sub-class. Checks that it really IS a sub-class object
  • static_cast<newtype>(?) - Cast between types, converting the type
  • reinterpret_cast<newtype>(?) - Interpret the bits in one type as another, mainly needed for low-level code, effects are often platform-dependent

This syntax makes the presence/purpose of casts more obvious

static_cast<type>(var)

  • Commonly used cast
  • Attempts to convert correctly between two types
  • Usually use this when not removing const-ness and there is no need to check the sub-class type at runtime

dynamic_cast<type(var)

  • Casting from derived class to base class is easy.
  • Safely convert from a base-class pointer or reference to a sub-class pointer or reference
  • Checks the type at run-time rather than compile-time
  • Returns NULL if the type conversion of a pointer cannot take place
  • There is no such thing as a NULL reference.

reinterpret_cast<type>(var)

  • Treat the value as if it was a different tyoe
  • Interpret the bits in one type as another
  • Including platform dependent conversions
  • Hardly ever needed, apart from with low-level code

Operator Overloading

  • Function overloading - Change the meaning of a function according to the types of the parameters
  • Operator Overloading - Change the meaning of an operator according to the types of the parameters

Restrictions

  • Cannot change an operators precedence
  • Cannot create new operators
  • Cannot provide default parameter values
  • Cannot change number of parameters (operands)
  • Cannot override some operators
  • Must overload +, += etc separately