(C++) operator

January 14, 2018 ยท View on GitHub

Keyword to overload an operator. An operator performs a function or member function.

Overview of operators (incomplete)

operatoroperator
address-of operator&
dereference operator*
assign operator=
bit shift left assign operator<<=
bit shift right assign operator>>=
bitwise and operator&
bitwise not operator~
bitwise or operator[
bitwise xor operator^
bitwise xor assign operator^=
comma operator,
decrement operator--
divide assign operator/=
divide operator/
equal operator==
function call operator()
greater than operator>
greater than or equal operator>=
increment operator++
index operator[
index operator[]
index operator]
less than operator<
less than or equal operator<=
logical and operator&&
logical not operator!
[
member access operator.
arrow operator->
minus assign operator-=
minus operator-
modulus assign operator%=
modulus operator%
multiply assign operator*=
multiply operator*
not equal operator!=
plus assign operator+=
plus operator+
questionmark colon operator?:
scope operator::
sizeof operatorsizeof
stream out operator<<

Advice

  • Use operator overloads judiciously [6]
  • Define operators primarily to mimic conventional usage [1]
  • Place spaces on either side of a binary operator [2]
  • Define operators consistently with each other and whenever appropriate provide semantics similar to those of standard types [3]
  • Pay attention that the semantic/intended priority of your overloaded operators matches the priorities of C++ operators [4]
  • Implement binary operators as free functions [5]

References

  • [1] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 17.7. Advice, page 547: '[1] Define operators primarily to mimic conventional usage'
  • [2] Paul Deitel, Harvey Deitel. C++11 for programmers (2nd edition). 2014. ISBN: 978-0-13-343985-4. Chapter 2.4, Good Programming Practice 2.7. page 28: 'Place spaces on either side of a binary operator. This will make the operator stand out and make the program more readable.'
  • [3] Gottschling, Peter. Discovering Modern C++: An Intensive Course for Scientists, Engineers, and Programmers. Addison-Wesley Professional, 2015. Chapter 2.7.1: 'Define your operators consistently with each other and whenever appropriate provide semantics similar to those of standard types'
  • [4] Gottschling, Peter. Discovering Modern C++: An Intensive Course for Scientists, Engineers, and Programmers. Addison-Wesley Professional, 2015. Chapter 2.7.2: 'Pay attention that the semantic/intended priority of your overloaded operators matches the priorities of C++ operators'
  • [5] Gottschling, Peter. Discovering Modern C++: An Intensive Course for Scientists, Engineers, and Programmers. Addison-Wesley Professional, 2015. Chapter 2.7.3: 'Implement binary operators as free functions'
  • [6] Jason Turner, cppbestpractices: Use Operator Overloads Judiciously