[CPP] Casting and operator overloading

Casting

Casting away the const-ness

When we have a const value, normally we can’t change them, but using casting, we can cast the const value to remove the constness of a reference or pointer.
enter image description here
WARNING: Do not actually do this unless there is a really good reason! Casting away const-ness is really bad.

C++11 new way to cast

enter image description here
Four new casts:
  • cosnt_cast< newtype >(?)
  • dynamic_cast < newtype >(?): safely cast a pointer or reference from base-class to sub-class
  • static_cast< newtype >(?): cast between types, converting the type
  • reinterpret_cast< newtype >(?)
Four types give more control over what you mean, and help you to identify the effects.
Sometimes needed : dynamic_cast provides run-time type checking.
Note: Casting a pointer will not usually change the stored address value, only the type. This is NOT true with multiple inheritance.

static_cast

Commonly used cast, attempts to convert correctly between two types.
The example is in the previous blog. You can use label [CPP] to find them.

dynamic_cast

  • Casting from derived class to base class is easy, because derived class object is a base class object.
  • But base class object might not be a derived class object.
  • Using dynamic_cast, 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.
  • If reference conversion fails, it throws an exception of type std::bad_cast
    enter image description here

reinterpret_cast< type >(var)

Usually this kind of cast is rarely used, and used on pointers(addresses)

Operator overloading

In C++, operators are implemented as functions. By using function overloading on the operator functions, you can define your own versions of the operators that work with different data types (including classes that you’ve written). Using function overloading to overload operators is called operator overloading.
- Function overloading: change the meaning of function according to the types of the parameters
- Operator overloading: change the meaning of operator according to the types of the parameters
enter image description here
enter image description here
What’s the difference between member function and non-member function?
enter image description here

Restriction

  • You cannot change an operator’s precedence
  • You cannot create new operators
  • You cannot change number of parameters (operands)
  • You cannot override some operators: :: sizeof ? : or . (dot)

评论

此博客中的热门博文

[MLE] W2 Multivariate linear regression

[MLE] W1 Introduction

[AIM] MetaHeuristics