C++ constexpr vs const

Poby’s Home
Feb 24, 2021

1. constexpr vs const

constexpr

  • known at compile time

const

  • means “promise not to change”
  • who promises not to change what?

2. const

const variable

  • const int pi

const reference

  • const Foo &foo

const pointer

  • char *const p

pointer to const

  • const char *p

const methods

  • promise that the method will not change the member variable
  • void method() const

C++ casting

static_cast

always defined behavior and known at compile time

dynamic_cast

always defined behavior but might fail at runtime. Used typically for inheritance relationship.

const_cast

only used to remove const. (your API design sucks! so go back and review your code)

reinterpret_cast

Forcing compiler to do what you want to do when you do something weird

(int)

don’t do this.

--

--