Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator overloading cheatsheet

Tags:

c++

Does anyone have a summary of boilerplate declarations for C++ operator overloading? A one page pdf would be nice. It would help us forgetful people having to stop and think about where to put our const and & and friend etc.

like image 569
wxffles Avatar asked Jan 23 '12 19:01

wxffles


2 Answers

Wikipedia has a pretty nice entry:

http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

Complete with prototypes for both member and global functions, where applicable.

like image 199
pezcode Avatar answered Nov 12 '22 20:11

pezcode


Summary:

  • Assignment and compound assignment operators must be members, not friends.

  • Use the copy-and-swap idiom and pass-by-value for assignment operators. This gives you exception safety and handles the "assign-to-self" case.

  • Operators where the custom class can appear as either operand should be friends.

like image 1
Ben Voigt Avatar answered Nov 12 '22 18:11

Ben Voigt