By sbi

2010-12-12 12:44:56 8 Comments

Note: The answers were given in a specific order, but since many users sort answers according to votes, rather than the time they were given, here's an index of the answers in the order in which they make most sense:

(Note: This is meant to be an entry to Stack Overflow's C++ FAQ. If you want to critique the idea of providing an FAQ in this form, then the posting on meta that started all this would be the place to do that. Answers to that question are monitored in the C++ chatroom, where the FAQ idea started out in the first place, so your answer is very likely to get read by those who came up with the idea.)


@sbi 2010-12-12 12:47:05

Common operators to overload

Most of the work in overloading operators is boiler-plate code. That is little wonder, since operators are merely syntactic sugar, their actual work could be done by (and often is forwarded to) plain functions. But it is important that you get this boiler-plate code right. If you fail, either your operator’s code won’t compile or your users’ code won’t compile or your users’ code will behave surprisingly.

Assignment Operator

There's a lot to be said about assignment. However, most of it has already been said in GMan's famous Copy-And-Swap FAQ, so I'll skip most of it here, only listing the perfect assignment operator for reference:

X& X::operator=(X rhs)
  return *this;

Bitshift Operators (used for Stream I/O)

The bitshift operators << and >>, although still used in hardware interfacing for the bit-manipulation functions they inherit from C, have become more prevalent as overloaded stream input and output operators in most applications. For guidance overloading as bit-manipulation operators, see the section below on Binary Arithmetic Operators. For implementing your own custom format and parsing logic when your object is used with iostreams, continue.

The stream operators, among the most commonly overloaded operators, are binary infix operators for which the syntax specifies no restriction on whether they should be members or non-members. Since they change their left argument (they alter the stream’s state), they should, according to the rules of thumb, be implemented as members of their left operand’s type. However, their left operands are streams from the standard library, and while most of the stream output and input operators defined by the standard library are indeed defined as members of the stream classes, when you implement output and input operations for your own types, you cannot change the standard library’s stream types. That’s why you need to implement these operators for your own types as non-member functions. The canonical forms of the two are these:

std::ostream& operator<<(std::ostream& os, const T& obj)
  // write obj to stream

  return os;

std::istream& operator>>(std::istream& is, T& obj)
  // read obj from stream

  if( /* no valid object of T found in stream */ )

  return is;

When implementing operator>>, manually setting the stream’s state is only necessary when the reading itself succeeded, but the result is not what would be expected.

Function call operator

The function call operator, used to create function objects, also known as functors, must be defined as a member function, so it always has the implicit this argument of member functions. Other than this, it can be overloaded to take any number of additional arguments, including zero.

Here's an example of the syntax:

class foo {
    // Overloaded call operator
    int operator()(const std::string& y) {
        // ...


foo f;
int a = f("hello");

Throughout the C++ standard library, function objects are always copied. Your own function objects should therefore be cheap to copy. If a function object absolutely needs to use data which is expensive to copy, it is better to store that data elsewhere and have the function object refer to it.

Comparison operators

The binary infix comparison operators should, according to the rules of thumb, be implemented as non-member functions1. The unary prefix negation ! should (according to the same rules) be implemented as a member function. (but it is usually not a good idea to overload it.)

The standard library’s algorithms (e.g. std::sort()) and types (e.g. std::map) will always only expect operator< to be present. However, the users of your type will expect all the other operators to be present, too, so if you define operator<, be sure to follow the third fundamental rule of operator overloading and also define all the other boolean comparison operators. The canonical way to implement them is this:

inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator!=(const X& lhs, const X& rhs){return !operator==(lhs,rhs);}
inline bool operator< (const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator> (const X& lhs, const X& rhs){return  operator< (rhs,lhs);}
inline bool operator<=(const X& lhs, const X& rhs){return !operator> (lhs,rhs);}
inline bool operator>=(const X& lhs, const X& rhs){return !operator< (lhs,rhs);}

The important thing to note here is that only two of these operators actually do anything, the others are just forwarding their arguments to either of these two to do the actual work.

The syntax for overloading the remaining binary boolean operators (||, &&) follows the rules of the comparison operators. However, it is very unlikely that you would find a reasonable use case for these2.

1 As with all rules of thumb, sometimes there might be reasons to break this one, too. If so, do not forget that the left-hand operand of the binary comparison operators, which for member functions will be *this, needs to be const, too. So a comparison operator implemented as a member function would have to have this signature:

bool operator<(const X& rhs) const { /* do actual comparison with *this */ }

(Note the const at the end.)

2 It should be noted that the built-in version of || and && use shortcut semantics. While the user defined ones (because they are syntactic sugar for method calls) do not use shortcut semantics. User will expect these operators to have shortcut semantics, and their code may depend on it, Therefore it is highly advised NEVER to define them.

Arithmetic Operators

Unary arithmetic operators

The unary increment and decrement operators come in both prefix and postfix flavor. To tell one from the other, the postfix variants take an additional dummy int argument. If you overload increment or decrement, be sure to always implement both prefix and postfix versions. Here is the canonical implementation of increment, decrement follows the same rules:

class X {
  X& operator++()
    // do actual increment
    return *this;
  X operator++(int)
    X tmp(*this);
    return tmp;

Note that the postfix variant is implemented in terms of prefix. Also note that postfix does an extra copy.2

Overloading unary minus and plus is not very common and probably best avoided. If needed, they should probably be overloaded as member functions.

2 Also note that the postfix variant does more work and is therefore less efficient to use than the prefix variant. This is a good reason to generally prefer prefix increment over postfix increment. While compilers can usually optimize away the additional work of postfix increment for built-in types, they might not be able to do the same for user-defined types (which could be something as innocently looking as a list iterator). Once you got used to do i++, it becomes very hard to remember to do ++i instead when i is not of a built-in type (plus you'd have to change code when changing a type), so it is better to make a habit of always using prefix increment, unless postfix is explicitly needed.

Binary arithmetic operators

For the binary arithmetic operators, do not forget to obey the third basic rule operator overloading: If you provide +, also provide +=, if you provide -, do not omit -=, etc. Andrew Koenig is said to have been the first to observe that the compound assignment operators can be used as a base for their non-compound counterparts. That is, operator + is implemented in terms of +=, - is implemented in terms of -= etc.

According to our rules of thumb, + and its companions should be non-members, while their compound assignment counterparts (+= etc.), changing their left argument, should be a member. Here is the exemplary code for += and +; the other binary arithmetic operators should be implemented in the same way:

class X {
  X& operator+=(const X& rhs)
    // actual addition of rhs to *this
    return *this;
inline X operator+(X lhs, const X& rhs)
  lhs += rhs;
  return lhs;

operator+= returns its result per reference, while operator+ returns a copy of its result. Of course, returning a reference is usually more efficient than returning a copy, but in the case of operator+, there is no way around the copying. When you write a + b, you expect the result to be a new value, which is why operator+ has to return a new value.3 Also note that operator+ takes its left operand by copy rather than by const reference. The reason for this is the same as the reason giving for operator= taking its argument per copy.

The bit manipulation operators ~ & | ^ << >> should be implemented in the same way as the arithmetic operators. However, (except for overloading << and >> for output and input) there are very few reasonable use cases for overloading these.

3 Again, the lesson to be taken from this is that a += b is, in general, more efficient than a + b and should be preferred if possible.

Array Subscripting

The array subscript operator is a binary operator which must be implemented as a class member. It is used for container-like types that allow access to their data elements by a key. The canonical form of providing these is this:

class X {
        value_type& operator[](index_type idx);
  const value_type& operator[](index_type idx) const;
  // ...

Unless you do not want users of your class to be able to change data elements returned by operator[] (in which case you can omit the non-const variant), you should always provide both variants of the operator.

If value_type is known to refer to a built-in type, the const variant of the operator should better return a copy instead of a const reference:

class X {
  value_type& operator[](index_type idx);
  value_type  operator[](index_type idx) const;
  // ...

Operators for Pointer-like Types

For defining your own iterators or smart pointers, you have to overload the unary prefix dereference operator * and the binary infix pointer member access operator ->:

class my_ptr {
        value_type& operator*();
  const value_type& operator*() const;
        value_type* operator->();
  const value_type* operator->() const;

Note that these, too, will almost always need both a const and a non-const version. For the -> operator, if value_type is of class (or struct or union) type, another operator->() is called recursively, until an operator->() returns a value of non-class type.

The unary address-of operator should never be overloaded.

For operator->*() see this question. It's rarely used and thus rarely ever overloaded. In fact, even iterators do not overload it.

Continue to Conversion Operators

@Matteo Italia 2010-12-12 12:58:59

Great FAQ, but what about mentioning sentry (…) for the insertion/extraction operators? I'd also expand a little the section about ->, e.g. making more clear how the return value is interpreted, etc.

@sbi 2010-12-12 13:10:53

@Matteo: I've been sitting all morning coming up with this, and I'm quite exhausted now. :) Why don't you add your own answer about that? You could copy from mine whatever you want, and we'd put a link to yours into mine instead of my text?

@Matteo Italia 2010-12-12 14:40:17

@sbi: I don't think it deserves a whole new answer, it was just a little improvement to yours that is already great (the first thing I've done was to upvote it :) ). Maybe I'll add something to the -> section later, I didn't understand sentry enough to write something about it.

@Yttrill 2010-12-12 14:56:20

Since you write up the comparison operators you must also comment on what semantics they should represent if implemented, in particular, what if you have a Partial Order? Do you think it is still OK to use the comparison operators?

@Yttrill 2010-12-12 15:03:03

Also it isn't so wise to say "a+=b" is more efficient that "a=a+b". Assumptions about performance are often wrong.

@Yttrill 2010-12-12 15:18:59

Please treat assignment completely separately. It's a very special operator because the semantics are broken.

@Matthieu M. 2010-12-12 15:39:41

@sbi: This is not the canonical form I know for >, I usually use: bool operator>(X const& lhs, X const& rhs) { return rhs < lhs; } Also perhaps it would be worth mentionning Boost.Operators here, since it takes care of this boilerplate code and gets it right :)

@sbi 2010-12-12 16:49:50

@Matthieu: I was expecting for you to show up and point out boost. :) Why don't you add it? As I said elsewhere, I never had a chance to use this, and now I'm forced to write C# for a living. :(

@sbi 2010-12-12 16:52:18

@Martin: I really don't see how this could be right. a<bis true if b>a, which is what my original implementation did. I don't see the point of yours at all. If operator< (rhs,lhs), then operator!=(lhs,rhs) will always hold.

@sbi 2010-12-12 16:53:59

@Token: Then you would be wrong, me thinks. IIRC, Pete Becker (then implementing Dinkumware's std lib implementation) once said that whoever overloads operator& for their types and still expect them to work with STL containers should be punished by having to implement an STL that achieves that.

@sbi 2010-12-12 20:04:43

@Yttrill: I wrote that a+=b is in general more efficient than a=a+b, because the latter does more work. I never said it's always so. (In fact, I usually get a lot of heat for answers like this one.

@sbi 2010-12-12 20:05:00

@Yttrill: I'm not sure what you want about assignment. It is treated in GMan's copy-and-swap question and all I do is link to that. How much more separate can a treatment get?

@j_random_hacker 2011-02-22 11:20:04

operator->() is actually extremely weird. It's not required to return a value_type* -- in fact, it can return another class type, provided that class type has an operator->(), which will then be called subsequently. This recursive calling of operator->()s proceeds until a value_type* return type occurs. Madness! :)

@sbi 2011-02-22 13:30:02

@j_random_hacker: I'm just trying to not to put too much information into these "basic rules". This answer is already very long. So I've upvoted your comment instead to make it visible above the rest of the commentary noise. However, feel free to add your information to the answer if you think it warrants being mentioned in the answer proper.

@James 2011-12-14 11:31:44

I think std::rel_ops deserves a mention, regarding comparison operators.

@sbi 2011-12-14 11:37:02

@Autopulated: This might well be true, but see my answer to Matthieu further up. Feel free to add it to my answer or add an answer of your own. We could mention that in the question.

@User 2012-04-20 00:05:45

@sbi: +1. But in your Comparison operators section, you list > last, but earlier operators depend on it for their implementation. When I copied and pasted this code it wouldn't compile because '>' wasn't defined (until later).

@Luc Hermitte 2012-10-11 13:03:11

Note that there are cases when defining operatorX in terms of operatorX= if not practical. For matrices and polynomials (english?), code factorization of the multiplication goes the other way: operator*= should be defined in terms of operator*.

@sbi 2012-10-11 13:14:53

@LucHermitte: I have yet to encounter a case where doing it the other way would be more effective, but I do not doubt that they exist. This is all rules of thumb, after all.

@Luc Hermitte 2012-10-11 14:02:21

It's not exactly about effectiveness. It's about we cannot do it in the traditional-idiomatic way in a (very) few cases: when the definition of both operands need to stay unchanged while we compute the result. And as I said, there are two classical examples: matrices multiplication, and multiplication of polynomials. We could define * in terms of *= but it would be awkward because one of the first operation of *= would to create a new object, result of the computation. Then, after the for-ijk loop, we would swap this temporary object with *this. ie. 1.copy, 2.operator*, 3.swap

@CTMacUser 2013-01-06 10:46:29

Defining operatorX in terms of operatorX= prevents the former from being constexpr, making it another case of switching which one derives from the other.

@Arne Mertz 2013-04-09 14:02:52

I disagree with the const/non-const versions of your pointer-like operators, e.g. ` const value_type& operator*() const;` - this would be like having a T* const returning a const T& on dereferencing, which is not the case. Or in other words: a const pointer does not imply a const pointee. In fact, it is not trivial to mimic T const * - which is the reason for the whole const_iterator stuff in the standard library. Conclusion: the signature should be reference_type operator*() const; pointer_type operator->() const

@sbi 2013-05-03 14:19:27

@Jkor: I'll gladly fully incorporate that, if you would expand on what the exact effects of doing so are. Alternatively, you can make your own answer about conversion operators, move my stuff there, and incorporate the explicit twist in C++11. I'd gladly work the link to that answer into the current TOC, so it would be fully exposed. (Similar to the answer on overloading new and delete.)

@JKor 2013-05-03 20:38:14

@sbi I would love to do that. I'm a little busy right now, but I'll try to get it done soon. Thanks for offering!

@Manu343726 2013-07-19 08:36:03

One comment: The implementation of binary arithmetic operators suggested is not such efficient as it can be. Se Boost operators headers simmetry note:‌​y One more copy can be avoided if you use a local copy of the first parameter, do +=, and return the local copy. This enables NRVO optimization.

@TemplateRex 2013-10-10 18:24:42

As I mentioned in the chat, L <= R can also be expressed as !(R < L) instead of !(L > R). Might save an extra layer of inlining in hard-to-optimize expressions (and it's also how Boost.Operators implements it).

@thomthom 2013-12-03 23:47:54

Trying when the rule of thumb doesn't apply. The == operator treat both objects as equal, but surely it often would need to access private members to compare - will that work when it's a non-member?

@sbi 2013-12-04 08:12:44

@thomthom: If a class doesn't have a publicly accessible API for getting at its state, you will have to either make everything that needs to access its state a member or a friend of the class. This, of course, is also true for all operators.

@sbi 2014-05-05 14:23:33

@juanchopanza: I rolled that back. You just traded one optimization (copy elision) for another (RVO), without giving a rationale why doing so is an improvement. (Feel free to discuss this and maybe you'll convince me.)

@juanchopanza 2014-05-05 14:26:07

@sbi Do you have an example of when your implementation would result in less copies than the one I proposed?

@sbi 2014-05-05 14:33:37

@juanchopanza: The website currently doesn't load for me, but Want Speed? Pass By Value! by Dave Abrahams is the canonical reference for this. (This seems to be a copy. I can't check it for accuracy, though.)

@juanchopanza 2014-05-05 14:36:09

@sbi I have read that. But I haven't seen a convincing example, just a lot of theorizing. I agree that it could help if you don't want to return the local copy, but if you do, I think it is at best the same as my example, but usually you incur more copies.

@sbi 2014-05-08 07:12:12

@juan: I thought the article gives a few if them, but here you go: a+b+c. The result of a+b is an rvalue that can be moved directly into the first argument for the second call to operator+.

@juanchopanza 2014-05-13 16:24:39

@sbi That relies on the type being efficiently movable. Anyway, I summarized some findings here:… My opinion is that you should be justifying your chosen form of operator+, not the other way around.

@Elegant Codeworks 2014-05-20 03:31:28

When overloading operator<<() and operator>>(), does the left hand side have to be streams, or is it such a standard practice that it's a hard recommendation?

@sbi 2014-05-20 05:49:49

@mindandsky At least one of the arguments must be a user-defined type. Otherwise you're free, syntactically. But commonly it's overloaded for streams, that's why I used that as an example.

@Pharap 2014-07-19 10:59:02

@Ben Voigt 2014-08-04 21:52:59

@sbi: Would you consider changing << and >> to "Bitshift Operators (used for Stream I/O)"? Their usage as stream I/O is not their primary function and doesn't match their precedence, although it's the one new programmers usually encounter first. And as you see in the comments, it has caused some confusion about whether those operators are only usable with streams (of course not).

@sbi 2014-08-04 21:55:55

@Ben: I think their primary use nowadays is for input and output, but I'd be fine with the proposed change anyway. Go ahead!

@vsoftco 2015-04-06 16:16:36

@sbi I know this is 5 years later, but why Array subscripting: "If value_type is known to refer to a built-in type, the const variant of the operator should return a copy instead of a const reference."? What's wrong with returning const reference all the time? Most of the time the class will be templated, so one doesn't know the type, but even if not, I don't see anything wrong with returning by const reference.

@sbi 2015-04-07 07:27:27

@vsoftco: These rules mirror those for passing arguments. Basically, you pass per const reference in order to avoid the overhead (and sometimes the semantics) of copying. For built-ins this is not an issue, because copying them is as cheap as (or cheaper than) copying an address (and their copy semantics is trivial).

@vsoftco 2015-04-07 07:31:54

@sbi thanks much, that's what I thought. Reading the post seems to enforce this though, and it shouldn't be an issue to return by const reference. That is, if you have some template, it makes no sense of using crazy std::enable_if to SFINAE out the return by const reference. So you can just say "always pass by const reference, although for PODs it won't make a difference". Anyway, great post (it became my reference for op. overloading).

@sbi 2015-04-07 07:41:51

@vsoftco: In a template, return by const reference. My original rules of thumb in that passing arguments answer (for C++03, later modified for C++11) advices to use const reference unless you... pass built-in types. In a template you do not know what types you pass, so the original advice there would prompt you to pass per const reference.

@vsoftco 2015-04-07 07:50:35

@sbi I get that, thanks, I just don't see why you have "except when they are of built-in types, which can be passed by copy". The "except when" enforces something. I'd just remove that altogether. Yes, they can be passed by copy (no overhead involved), but it's equally fine if you pass them by const reference. I'm just saying this because I saw some recent questions/answers on SO that promote this kind of thing, like testing whether your type is POD, if yes, return by value, if not, return by const ref, which imo makes no sense. In C++11 I agree things change because of move semantics.

@Étienne 2015-06-07 18:10:26

Did I miss something obvious? The comparison operators will not compile if defined like explained in this post, the keyword "friend" is missing, at least when defining those operators inside a class.

@sbi 2015-06-07 23:43:03

@Etienne: I cannot make sense of what you said. Please elaborate where you would put a friend.

@sbi 2015-06-08 08:48:48

@Etienne: Read this FAQ. It explains why you ran into problems (and thereby why friend solves your problems, but might not be what you actually want). If you are in such a terrible hurry that you cannot even be bothered to fully read a simple FAQ before jumping into coding, C++ might not be suited to you. (Most people need a good book to learn it.) I suggest you start at the beginning of this FAQ and try to understand all of it, but if you're too lazy to do that, read at least this.

@sbi 2015-06-08 08:57:29

@Etienne: The reason this doesn't compile is that you're doing it wrong. The reason you're doing it wrong it's that you don't understand it. The rain you don't understand it is that you didn't take the time to learn it. Again: My code compiles fine as it is. If you use it right. Adding friend is unlikely to be what you want.

@Étienne 2015-06-08 09:01:03

I fully understand the problem and the difference between friend and non-friend. I mostly saw comparison operators declared as friend functions, that's why I considered friend function to be the canonical way and wanted to help improve this answer. This is okay to leave it like it is since my idea of canonical seems to be wrong but there is no need to call me lazy for this.

@sbi 2015-06-08 09:44:46

@Etienne: This is the moment I give up. HAND.

@beauxq 2015-11-25 16:11:10

Is any efficiency lost from implementing > <= >= in terms of <?

@sbi 2015-11-25 17:29:47

@beauxq: Not if the compiler can inline the forwarding calls. (Given that they are trivial, this should not be a problem.)

@skypjack 2016-06-10 05:49:09

@sbi According with this question and, footnote-129, return type for operator-> is a bit more interesting argument than what is described above. As an example, double operator->() seems to be a valid syntax (even if useless, of course).

@sbi 2016-06-14 07:21:01

@skypjack: You might want to look at the most-upvoted comment above yours and my answer to it. :) Nevertheless, since this came up for the second time, and since it seems my wording was actually wrong, I changed it. Feel free to improve if you want to.

@UKMonkey 2016-09-30 16:37:26

@sbi Just highlighting that the assignment operator here isn't the perfect example for 99% of cases, as you don't want to change the rhs. For me, the perfect one would have a const rhs.

@sbi 2016-10-03 19:26:59

@UKMonkey: And how do you swap your state with a constant object??

@UKMonkey 2016-10-04 08:55:09

@sbi That's the point; the assignment operator shouldn't be swapping state, it should be assigning the LHS to the RHS, and not changing the RHS at all; except in rare situations, eg std::auto_ptr

@sbi 2016-10-06 08:05:38

@UKMonkey: Why don't you just follow the link that I provided? There, GMan explained in painful length why you are about 10-15 years behind the state of the art with this assumption.

@Jon Cage 2017-05-03 16:25:36

I tried implementing operator| as per your suggestion to follow arithmetic rules but this doesn't compile because I have the wrong number of arguments inline X operator|(X lhs, const X &rhs) ?

@sbi 2017-05-07 20:44:19

@Jon: That would be the free function implementation. You didn't put this into a class, did you? Read here: "A binary infix operator @, applied to the objects x and y, is called either as [email protected](x,y) or as [email protected](y)."

@Toby Speight 2018-07-11 11:08:25

The section on comparison operators will need an update to mention operator<=>() when that's final (C++20).

@sbi 2018-07-12 06:11:10

@Toby Indeed. Thanks for pointing this out. However, this guide's goal is to present experience and common wisdom collected over the years, and any text about operator<=>, because of it being brand new, will not be up to that standard. But I guess that can't be helped.

@Andrew Keeton 2018-11-29 19:39:18

"Also note that operator+ takes its left operand by copy rather than by const reference. The reason for this is the same as the reason giving for operator= taking its argument per copy." I want to make sure I understand: a copy is required to reuse operator+= no matter what, so (1) we save typing by letting the compiler do it, and (2) the compiler can perform copy elision and move construction for performance.

@sbi 2018-12-01 14:06:38

@Andrew: That's the diea (although move-construction didn't even exist on paper when that idiom was come up with).

@Juan Carlos Ramirez 2019-03-14 15:39:14

@sbi On array subscripting, if your index_type is expensive to copy, shouldn't you pass it by const reference?

@sbi 2019-06-06 09:22:13

@JuanCarlosRamirez: Yes, if your index type isn't a cheap one to copy (like in std::map<std::string,...>, then it should be passed according to these rules.

@sbi 2010-12-12 13:07:17

Overloading new and delete

Note: This only deals with the syntax of overloading new and delete, not with the implementation of such overloaded operators. I think that the semantics of overloading new and delete deserve their own FAQ, within the topic of operator overloading I can never do it justice.


In C++, when you write a new expression like new T(arg) two things happen when this expression is evaluated: First operator new is invoked to obtain raw memory, and then the appropriate constructor of T is invoked to turn this raw memory into a valid object. Likewise, when you delete an object, first its destructor is called, and then the memory is returned to operator delete.
C++ allows you to tune both of these operations: memory management and the construction/destruction of the object at the allocated memory. The latter is done by writing constructors and destructors for a class. Fine-tuning memory management is done by writing your own operator new and operator delete.

The first of the basic rules of operator overloading – don’t do it – applies especially to overloading new and delete. Almost the only reasons to overload these operators are performance problems and memory constraints, and in many cases, other actions, like changes to the algorithms used, will provide a much higher cost/gain ratio than attempting to tweak memory management.

The C++ standard library comes with a set of predefined new and delete operators. The most important ones are these:

void* operator new(std::size_t) throw(std::bad_alloc); 
void  operator delete(void*) throw(); 
void* operator new[](std::size_t) throw(std::bad_alloc); 
void  operator delete[](void*) throw(); 

The first two allocate/deallocate memory for an object, the latter two for an array of objects. If you provide your own versions of these, they will not overload, but replace the ones from the standard library.
If you overload operator new, you should always also overload the matching operator delete, even if you never intend to call it. The reason is that, if a constructor throws during the evaluation of a new expression, the run-time system will return the memory to the operator delete matching the operator new that was called to allocate the memory to create the object in. If you do not provide a matching operator delete, the default one is called, which is almost always wrong.
If you overload new and delete, you should consider overloading the array variants, too.

Placement new

C++ allows new and delete operators to take additional arguments.
So-called placement new allows you to create an object at a certain address which is passed to:

class X { /* ... */ };
char buffer[ sizeof(X) ];
void f()
  X* p = new(buffer) X(/*...*/);
  // ... 
  p->~X(); // call destructor 

The standard library comes with the appropriate overloads of the new and delete operators for this:

void* operator new(std::size_t,void* p) throw(std::bad_alloc); 
void  operator delete(void* p,void*) throw(); 
void* operator new[](std::size_t,void* p) throw(std::bad_alloc); 
void  operator delete[](void* p,void*) throw(); 

Note that, in the example code for placement new given above, operator delete is never called, unless the constructor of X throws an exception.

You can also overload new and delete with other arguments. As with the additional argument for placement new, these arguments are also listed within parentheses after the keyword new. Merely for historical reasons, such variants are often also called placement new, even if their arguments are not for placing an object at a specific address.

Class-specific new and delete

Most commonly you will want to fine-tune memory management because measurement has shown that instances of a specific class, or of a group of related classes, are created and destroyed often and that the default memory management of the run-time system, tuned for general performance, deals inefficiently in this specific case. To improve this, you can overload new and delete for a specific class:

class my_class { 
    // ... 
    void* operator new();
    void  operator delete(void*,std::size_t);
    void* operator new[](size_t);
    void  operator delete[](void*,std::size_t);
    // ... 

Overloaded thus, new and delete behave like static member functions. For objects of my_class, the std::size_t argument will always be sizeof(my_class). However, these operators are also called for dynamically allocated objects of derived classes, in which case it might be greater than that.

Global new and delete

To overload the global new and delete, simply replace the pre-defined operators of the standard library with our own. However, this rarely ever needs to be done.

@Yttrill 2010-12-12 15:14:32

I also don't agree that replacing the global operator new and delete is usually for performance: on the contrary, it's usually for bug tracing.

@Yttrill 2010-12-12 15:17:11

You should also note, that if you use an overloaded new operator you're required to also provide a delete operator with matching arguments. You say that in the section on global new/delete where it isn't of much interest.

@sbi 2010-12-12 19:47:09

@Yttrill: Which tytle are you referring to? This answer's title is "Overloading new and delete". How does this contradict itself? And "confusing description" is quite a broad critique. How am I supposed to know what you expect?

@sbi 2010-12-12 19:47:25

@Yttrill: IME overloading new and delete was rarely done for finding actual bugs. But that might be because I pushed hard for using RAII where I worked, thus eliminating such bugs altogether.

@sbi 2010-12-12 19:47:56

@Yttrill:I say about providing a matching operator delete for every operator new in the Basics section. In the section about global new/delete there are only two sentences, and non of them refers to this. What am I missing?

@Johannes Schaub - litb 2010-12-13 04:51:28

@Yttrill you are confusing things. The meaning gets overloaded. What "operator overloading" means is that the meaning is overloaded. It does not mean that literally functions are overloaded, and in particular operator new will not overload the Standard's version. @sbi doesn't claim the opposite. It's common to call it "overloading new" much as it is common to say "overloading addition operator".

@Alexandre C. 2011-07-27 07:30:47

What about nothrow new ? The rule of thumb is that whenever you overload new, you must write 12 functions: [array] [{ placement | nothrow }] { new | delete }.

@sbi 2011-07-27 07:39:56

@Alexandre: This whole FAQ entry is distilled from guidelines I use for teaching C++, and since nothrow new is more or less just for legacy stuff, I haven't ever even mentioned it. What would you suggest should be written about it here?

@Alexandre C. 2011-07-27 08:36:29

@sbi: See (or better, link to) . It is only good practice towards people which sometimes use nothrow new.

@curiousguy 2011-12-02 12:17:12

new(buffer) X(/*...*/) what actually guarantees that buffer is properly aligned for X?

@unixman83 2012-03-23 04:57:11

This part of the FAQ needs improving. One thing: A major reason to overload operator new and delete is not for performance, but usually because of debugging and extremely constrained memory systems.

@sbi 2012-03-23 08:40:49

@unixman83: Memory performance is performance, too. :) Seriously: You are right, I will add that to the answer. Thanks for pointing it out. I disagree about debugging, though. IME it's much better to use 3rd-party tools than to cook up your own amateur's tools. Also, I consider memory leaks more a problem of your programming style ´, rather than of your tools. I haven't had to hunt for memory leaks in what by now probably is a decade.

@dascandy 2015-01-23 20:30:54

"If you do not provide a matching operator delete, the default one is called" -> Actually, if you add any arguments and do not create a matching delete, no operator delete is called at all, and you have a memory leak. (15.2.2, the storage occupied by the object is deallocated only if an appropriate ... operator delete is found)

@R Sahu 2016-01-22 19:00:54

Why can't operator<< function for streaming objects to std::cout or to a file be a member function?

Let's say you have:

struct Foo
   int a;
   double b;

   std::ostream& operator<<(std::ostream& out) const
      return out << a << " " << b;

Given that, you cannot use:

Foo f = {10, 20.0};
std::cout << f;

Since operator<< is overloaded as a member function of Foo, the LHS of the operator must be a Foo object. Which means, you will be required to use:

Foo f = {10, 20.0};
f << std::cout

which is very non-intuitive.

If you define it as a non-member function,

struct Foo
   int a;
   double b;

std::ostream& operator<<(std::ostream& out, Foo const& f)
   return out << f.a << " " << f.b;

You will be able to use:

Foo f = {10, 20.0};
std::cout << f;

which is very intuitive.

@JKor 2013-05-17 18:32:00

Conversion Operators (also known as User Defined Conversions)

In C++ you can create conversion operators, operators that allow the compiler to convert between your types and other defined types. There are two types of conversion operators, implicit and explicit ones.

Implicit Conversion Operators (C++98/C++03 and C++11)

An implicit conversion operator allows the compiler to implicitly convert (like the conversion between int and long) the value of a user-defined type to some other type.

The following is a simple class with an implicit conversion operator:

class my_string {
  operator const char*() const {return data_;} // This is the conversion operator
  const char* data_;

Implicit conversion operators, like one-argument constructors, are user-defined conversions. Compilers will grant one user-defined conversion when trying to match a call to an overloaded function.

void f(const char*);

my_string str;
f(str); // same as f( str.operator const char*() )

At first this seems very helpful, but the problem with this is that the implicit conversion even kicks in when it isn’t expected to. In the following code, void f(const char*) will be called because my_string() is not an lvalue, so the first does not match:

void f(my_string&);
void f(const char*);


Beginners easily get this wrong and even experienced C++ programmers are sometimes surprised because the compiler picks an overload they didn’t suspect. These problems can be mitigated by explicit conversion operators.

Explicit Conversion Operators (C++11)

Unlike implicit conversion operators, explicit conversion operators will never kick in when you don't expect them to. The following is a simple class with an explicit conversion operator:

class my_string {
  explicit operator const char*() const {return data_;}
  const char* data_;

Notice the explicit. Now when you try to execute the unexpected code from the implicit conversion operators, you get a compiler error:

prog.cpp: In function ‘int main()’:
prog.cpp:15:18: error: no matching function for call to ‘f(my_string)’
prog.cpp:15:18: note: candidates are:
prog.cpp:11:10: note: void f(my_string&)
prog.cpp:11:10: note:   no known conversion for argument 1 from ‘my_string’ to ‘my_string&’
prog.cpp:12:10: note: void f(const char*)
prog.cpp:12:10: note:   no known conversion for argument 1 from ‘my_string’ to ‘const char*’

To invoke the explicit cast operator, you have to use static_cast, a C-style cast, or a constructor style cast ( i.e. T(value) ).

However, there is one exception to this: The compiler is allowed to implicitly convert to bool. In addition, the compiler is not allowed to do another implicit conversion after it converts to bool (a compiler is allowed to do 2 implicit conversions at a time, but only 1 user-defined conversion at max).

Because the compiler will not cast "past" bool, explicit conversion operators now remove the need for the Safe Bool idiom. For example, smart pointers before C++11 used the Safe Bool idiom to prevent conversions to integral types. In C++11, the smart pointers use an explicit operator instead because the compiler is not allowed to implicitly convert to an integral type after it explicitly converted a type to bool.

Continue to Overloading new and delete.

@sbi 2010-12-12 12:46:30

The General Syntax of operator overloading in C++

You cannot change the meaning of operators for built-in types in C++, operators can only be overloaded for user-defined types1. That is, at least one of the operands has to be of a user-defined type. As with other overloaded functions, operators can be overloaded for a certain set of parameters only once.

Not all operators can be overloaded in C++. Among the operators that cannot be overloaded are: . :: sizeof typeid .* and the only ternary operator in C++, ?:

Among the operators that can be overloaded in C++ are these:

  • arithmetic operators: + - * / % and += -= *= /= %= (all binary infix); + - (unary prefix); ++ -- (unary prefix and postfix)
  • bit manipulation: & | ^ << >> and &= |= ^= <<= >>= (all binary infix); ~ (unary prefix)
  • boolean algebra: == != < > <= >= || && (all binary infix); ! (unary prefix)
  • memory management: new new[] delete delete[]
  • implicit conversion operators
  • miscellany: = [] -> ->* , (all binary infix); * & (all unary prefix) () (function call, n-ary infix)

However, the fact that you can overload all of these does not mean you should do so. See the basic rules of operator overloading.

In C++, operators are overloaded in the form of functions with special names. As with other functions, overloaded operators can generally be implemented either as a member function of their left operand's type or as non-member functions. Whether you are free to choose or bound to use either one depends on several criteria.2 A unary operator @3, applied to an object x, is invoked either as [email protected](x) or as [email protected](). A binary infix operator @, applied to the objects x and y, is called either as [email protected](x,y) or as [email protected](y).4

Operators that are implemented as non-member functions are sometimes friend of their operand’s type.

1 The term “user-defined” might be slightly misleading. C++ makes the distinction between built-in types and user-defined types. To the former belong for example int, char, and double; to the latter belong all struct, class, union, and enum types, including those from the standard library, even though they are not, as such, defined by users.

2 This is covered in a later part of this FAQ.

3 The @ is not a valid operator in C++ which is why I use it as a placeholder.

4 The only ternary operator in C++ cannot be overloaded and the only n-ary operator must always be implemented as a member function.

Continue to The Three Basic Rules of Operator Overloading in C++.

@curiousguy 2011-12-01 12:26:48

%= is not a "bit manipulation" operator

@mrkj 2012-11-02 05:15:27

~ is unary prefix, not binary infix.

@celticminstrel 2015-07-04 05:35:17

.* is missing from the list of non-overloadable operators.

@sbi 2015-07-04 19:56:02

@celticminstrel: Indeed, and nobody noticed for 4.5 years... Thanks for pointing it out, I put it in.

@celticminstrel 2015-07-04 21:11:55

non-overloadable! So, up there with . and ::. And, it's probably because most people never use pointers-to-members.

@sbi 2015-07-04 22:24:48

@celticminstrel: I was reading/writing .*, but thinking ->*, and therefore overlooking your non-overloadable. Anyway, the list of non-overloadable operators is not meant to be exhaustive ("Among the operators that cannot be overloaded..."), but since ->* was missing, I'll edit it in.

@Mateen Ulhaq 2015-09-09 01:03:14

Isn't it a bit confusing to use @ instead of a real example of a unary/binary operator? Some may mistakenly assume @ is actually an operator that is overloadable. (EDIT: I realize you've pointed this out in the postscript, but no one reads the postscript.)

@sbi 2015-09-11 10:57:02

@Mateen I wanted to use a placeholder instead of a real operator in order to make clear that this isn't about a special operator, but applies to all of them. And, if you want to be a C++ programmer, you should learn to pay attention even to the smallprint. :)

@Rory Yorke 2015-12-12 11:04:40

->* is listed both as an operator that cannot be overloaded, and, under miscellany, as one that can be.

@sbi 2015-12-12 19:56:20

@Rory: It seems bruziuz did this in his edit a few days ago, and I missed it. Thanks for pointing it out! I fixed it.

@H. R. 2018-07-13 14:47:25

I am a beginner and I use code:blocks. When I use operator+(x,y) for overloading the plus operator I get an error that the operator can only take one argument! :(

@sbi 2018-07-13 23:11:02

@H.R.: Had you read this guide, you would know what's wrong. I generally suggest that you should read the the first three answers linked from the question. That shouldn't be more than half an hour of your life, and gives you a basic understanding. The operator-specific syntax you can look up later. Your specific problem suggests you try to overload operator+() as a member function, but gave it the signature of a free function. See here.

@H. R. 2018-07-14 02:00:18

@sbi: I have read the three first post already and thank you for making them. :) I will try resolve the problem otherwise I think that it is better to ask it on a separate question. Thank you again for making life so easy for us! :D

@sbi 2010-12-12 12:49:13

The Decision between Member and Non-member

The binary operators = (assignment), [] (array subscription), -> (member access), as well as the n-ary () (function call) operator, must always be implemented as member functions, because the syntax of the language requires them to.

Other operators can be implemented either as members or as non-members. Some of them, however, usually have to be implemented as non-member functions, because their left operand cannot be modified by you. The most prominent of these are the input and output operators << and >>, whose left operands are stream classes from the standard library which you cannot change.

For all operators where you have to choose to either implement them as a member function or a non-member function, use the following rules of thumb to decide:

  1. If it is a unary operator, implement it as a member function.
  2. If a binary operator treats both operands equally (it leaves them unchanged), implement this operator as a non-member function.
  3. If a binary operator does not treat both of its operands equally (usually it will change its left operand), it might be useful to make it a member function of its left operand’s type, if it has to access the operand's private parts.

Of course, as with all rules of thumb, there are exceptions. If you have a type

enum Month {Jan, Feb, ..., Nov, Dec}

and you want to overload the increment and decrement operators for it, you cannot do this as a member functions, since in C++, enum types cannot have member functions. So you have to overload it as a free function. And operator<() for a class template nested within a class template is much easier to write and read when done as a member function inline in the class definition. But these are indeed rare exceptions.

(However, if you make an exception, do not forget the issue of const-ness for the operand that, for member functions, becomes the implicit this argument. If the operator as a non-member function would take its left-most argument as a const reference, the same operator as a member function needs to have a const at the end to make *this a const reference.)

Continue to Common operators to overload.

@paercebal 2010-12-12 13:36:08

Herb Sutter's item in Effective C++ (or is it C++ Coding Standards?) says one should prefer non-member non-friend functions to member functions, to increase the encapsulation of the class. IMHO, the encapsulation reason takes precedence to your rule of thumb, but it does not decrease the quality value of your rule of thumb.

@sbi 2010-12-12 13:39:35

@paercebal: Effective C++ is by Meyers, C++ Coding Standards by Sutter. Which one are you referring to? Anyway, I dislike the idea of, say, operator+=() not being a member. It has to change its left-hand operand, so by definition it has to dig deep into its innards. What would you gain by not making it a member?

@Karl von Moor 2010-12-12 13:49:23

@paercebal You are referring to Effective C++ by Meyers, not Sutter.

@sbi 2010-12-12 13:56:31

@Polybos: Which item is that in EC++?

@Matthieu M. 2010-12-12 15:45:00

@sbi: Item 44 in C++ Coding Standards (Sutter) Prefer writing nonmember nonfriend functions, of course, it only applies if you can actually write this function using only the public interface of the class. If you cannot (or can but it would hinder performance badly), then you have to make it either member or friend.

@paercebal 2010-12-12 16:51:07

@sbi : Oops, Effective, Exceptional... No wonder I mix the names up. Anyway the gain is to limit as much as possible the number of functions that have access to an object private/protected data. This way, you increase the encapsulation of your class, making its maintenance/testing/evolution easier.

@paercebal 2010-12-12 16:58:09

@sbi : One example. Let's say you're coding a String class, with both the operator += and the append methods. The append method is more complete, because you can append a substring of the parameter from index i to index n -1: append(string, start, end) It seems logical to have += call append with start = 0 and end = string.size. At that moment, append could be a member method, but operator += doesn't need to be a member, and making it a non-member would decrease the quantity of code playing with the String innards, so it is a good thing.... ^_^ ...

@sbi 2010-12-12 17:24:29

@paercebal: (Did you know there's also Efficient C++?) I see. If you had an append() method to your string class, += could indeed be a non-member. But, for one, using + and += for strings is questionable at best (isn't + supposed to b be commutative?) and only alright because it's based on existing praxis. Also, even though I do agree with Sutter on this (BTW, I think it was Meyers who first published an article on non-members actually improving encapsulation, hence my confusion) I might still make += a member for the very same reason: existing praxis.

@paercebal 2010-12-12 17:47:09

@sbi : I did know about both Sutter and Meyers books: I own almost all of them.

@paercebal 2010-12-12 17:56:30

@sbi : Commutativity should not be a criterion. For example, Matrices multiplication is not commutative, while number multiplication is. Should I be forbidden to overload * for matrices just because the C++ native integer * is commutative? No. Here, the principle of least surprise apply, and we must analyze an operator according to its context (i.e. its parameters). The same goes for strings and operator + (and by extension, +=). The fact is, no one expects the + operator to be commutative on strings, so, where's the problem with that?

@paercebal 2010-12-12 18:00:46

@sbi : Now, the existing practice about an operator could apply to an interface (e.g. provide + and += operators on strings because users do expect them), it should not be used to decide the implementation detail IMHO (e.g. decide += is to be member or non-member). This implementation detail is not about personal preference of taste: Decreasing the quantity of code accessing private data (i.e. encapsulation) is a good thing, and can be measured, so it should be pursued as much as possible (as long as the code remains clear, readable and correct, of course)

@j_random_hacker 2010-12-12 18:05:40

It's definitely better to implement either + or += outside the class (and likewise for the other operators @ that come with a @= version) for the reason paercebal gave. Here's an idea: since += is usually more efficient, implement += inside the class, and then have a templated operator+() that is enabled using enable_if only for classes T for which want_helper_ops<T> is defined. Nuke that boilerplate! :)

@sbi 2010-12-12 20:00:20

@paercebal: Yes, using << and >> for IO and + for string concatenation is established praxis. And I'm not opposed to any of them. What I'm saying is that there are arguments against doing so, and that, until it is established praxis, according my Three Basic Rules, to it shouldn't be done. (Yes I know it can't become established praxis unless you violate rule #1.) As for making += a non-member: Yes, it seems logical, but it never occurred to me, because I overload operators by those three rules for more than a decade. And such long-nursed habits die hard.

@sbi 2010-12-12 20:01:32

@j_random_hacker: The question is not whether one of them should be non-member, I think that's unanimously clear. The question is whether both of them should. See me previous comment to paercebal regarding this.

@Johannes Schaub - litb 2010-12-13 04:46:25

This rule sounds weird: If a binary operator does not treat both of its operands equally (usually it will change its left operand), it should be a member function of its left operand’s type.. The motivation for making it a member is not that both operands aren't treated equal. I think you should reword that item. An operator/ that does numeric division will treat the left operand different from the right. Still it should be written as a non-member.

@paercebal 2010-12-13 09:38:59

@sbi : "And such long-nursed habits die hard." : I know... I'm trying to get rid of my hungarian notation habit... :-(

@sbi 2010-12-13 15:04:16

@Johannes: If an operator changes its left-hand operand, it needs access to its innards.

@paercebal 2010-12-14 10:38:18

@sbi : "If an operator changes its left-hand operand, it needs access to its innards". No: The operator could use a method, so it doesn't need to have access to protected/private member. Again, in my example for strings, operator += doesn't need to access private members. It only needs only call the public append method with the right parameters.

@sbi 2010-12-14 10:54:01

@paercebal: I changed the wording somewhat. Do you approve of this now or does it need further changes?

@paercebal 2010-12-14 21:38:39

@sbi : After thinking about it, the list should be something like: 1. "if possible, make it non-member non-friend", 2. "The following operators are available only as member-functions: ...". . . Everything else seems a matter of taste. My own viewpoint on the subject is similar to yours, but it is still a matter of taste, and this excellent question/answers set should not be tainted by personal tastes. It should be the reference, motivated only by rock hard reasons.

@sbi 2010-12-14 22:13:00

@paercebal: But I consider "if possible..." too vague for a rule of thumb. And that's what I'm trying to hand out here: an easy-to-remember rule of thumb, which you can remember even if you can't remember all the reasoning. As it now is, my rule is basically saying "make it a non-member, if it's changing the left operand, consider membership". If most of you out there don't think this is enough, I will change t. But "if possible..." isn't enough to improve what I now have.

@paercebal 2010-12-15 11:00:16

@sbi : For me, the "if possible..." means "if it compiles...". Some operators must be member functions. For the others, I guess non-member functions should be preferred anyway, even if friend, because these authorizes a cast from some value into the class value (e.g. having the code MyInteger m(42), n ; n = 25 + m ; work).

@paercebal 2010-12-15 11:00:35

@sbi : With your authorization, I could think about an alternate list of items, and write it as a "proposition" at the end of the post (the comments are not suited for this lengthy discussion). Another possibility would be to contact me by email (append "@" + "gmail" + "." + "com" to my identifier)

@sbi 2010-12-15 11:56:07

@paercebal: If it's too long for comments, why don't we discuss this in the C++ chat? That's where the whole FAQ idea started out. It's pretty quiet there now (and I can't do online discussions now either), but in about 5-10hrs it usually looks very different. (If you want, you can post your ideas there now anyway, they won't get lost.)

@Andrew Falanga 2012-09-26 16:34:32

@sbi I only just saw this thread and I hope this question will be answered though this thread is nearly 2 years old now. With respect to overloading the binary operators, why should the operator not be a member function if it treats both operands equally (or doesn't change their innards)?

@Dennis 2013-08-17 07:30:29

@AndrewFalanga this comment answers your question:…

@Dennis 2013-08-17 07:32:35

Is there a recommended place for helper (non-member) functions? In the same file as the class, or in a separate file but in the same namespace as the class?

@sbi 2013-08-17 10:41:12

@Dennis: If they are part of the class' interface (like widget operator+(const widget&, const widget&) or void normalize(widget&), they should be in the class' namespace and close to the class' declaration. If they are merely private helpers, hide them in (the unnamed namespace of) the .cpp file or, should everything be in headers, in some namespace details.

@mlpo 2014-12-21 16:59:45

I may be wrong, but I feel that the case of the unary minus operator is forgotten (-a)… The rules of thumb states that “If it is a unary operator, implement it as a member function.”, but unary minus operator is a unary operator, yet it would be more logical to implement this operator as a non-member function (because after all, it leaves the operand unchanged). By the way, the same holds for unary plus operator.

@sbi 2014-12-22 13:52:17

@mlpo: As far as I can see I hadn't even mentioned unary minus anywhere except on the list of operators to overload. That's clearly an oversight, caused by unary minus not being very useful to overload at all. In fact, I don't believe that among the horrible abuse of operator overloading I have seen in >20 years was a single case of an overloaded unary minus operator. Nevertheless, thanks for pointing this out. I have now at least mentioned them. As per the rules, I'd made them members. Seems fitting to me.

@mlpo 2014-12-23 15:29:59

@sbi, the unary minus operator can sometimes be useful when adding two objects is really complex, we write the addition once and then we can implement the subtraction operator by writing a + (-b). This prevents code replication.

@mlpo 2014-12-23 15:42:07

Furthermore, I am not sure that the rule is logical, because unary minus operator leaves the operand unchanged and therefore in the same way as addition, it should be non-member function, right?

@sbi 2015-02-26 08:51:57

@mlpo: 1. You could just as well implement the subtraction with + ( without adding a minus operator to the class. (Of course, if the class is supposed to be a number type, then operator-() (and operator+()) should be part of the interface as per rule #3 here.) 2. As per rule #1 above unary operators should be members, no matter whether they change the object. (Besides prefix increment/decrement I can't think of any that do.) That's because you rarely want to conversions etc. applied to them.

@sbi 2010-12-12 12:45:14

The Three Basic Rules of Operator Overloading in C++

When it comes to operator overloading in C++, there are three basic rules you should follow. As with all such rules, there are indeed exceptions. Sometimes people have deviated from them and the outcome was not bad code, but such positive deviations are few and far between. At the very least, 99 out of 100 such deviations I have seen were unjustified. However, it might just as well have been 999 out of 1000. So you’d better stick to the following rules.

  1. Whenever the meaning of an operator is not obviously clear and undisputed, it should not be overloaded. Instead, provide a function with a well-chosen name.
    Basically, the first and foremost rule for overloading operators, at its very heart, says: Don’t do it. That might seem strange, because there is a lot to be known about operator overloading and so a lot of articles, book chapters, and other texts deal with all this. But despite this seemingly obvious evidence, there are only a surprisingly few cases where operator overloading is appropriate. The reason is that actually it is hard to understand the semantics behind the application of an operator unless the use of the operator in the application domain is well known and undisputed. Contrary to popular belief, this is hardly ever the case.

  2. Always stick to the operator’s well-known semantics.
    C++ poses no limitations on the semantics of overloaded operators. Your compiler will happily accept code that implements the binary + operator to subtract from its right operand. However, the users of such an operator would never suspect the expression a + b to subtract a from b. Of course, this supposes that the semantics of the operator in the application domain is undisputed.

  3. Always provide all out of a set of related operations.
    Operators are related to each other and to other operations. If your type supports a + b, users will expect to be able to call a += b, too. If it supports prefix increment ++a, they will expect a++ to work as well. If they can check whether a < b, they will most certainly expect to also to be able to check whether a > b. If they can copy-construct your type, they expect assignment to work as well.

Continue to The Decision between Member and Non-member.

@Billy ONeal 2010-12-12 17:50:52

The only thing of which I am aware which violates any of these is boost::spirit lol.

@sbi 2010-12-12 19:56:25

@Billy: According to some, abusing + for string concatenation is a violation, but it has by now become well established praxis, so that it seems natural. Although I do remember a home-brew string class I saw in the 90ies that used binary & for this purpose (referring to BASIC for established praxis). But, yeah, putting it into the std lib basically set this in stone. The same goes for abusing << and >> for IO, BTW. Why would left-shifting be the obvious output operation? Because we all learned about it when we saw our first "Hello, world!" application. And for no other reason.

@curiousguy 2011-12-01 12:18:57

"the meaning of an operator is not obviously clear and undisputed" and how do you determine that?

@sbi 2011-12-02 12:09:36

@curiousguy: If you have to explain it, it's not obviously clear and undisputed. Likewise if you need to discuss or defend the overloading.

@curiousguy 2011-12-02 12:11:59

So overloading == for containers is an abuse?

@Emilio Garavaglia 2012-04-09 07:58:42

This seems good sense, but has drawbacks: Point 1 will make boost::spirit impossible to exist, and the same can apply to iostream (does cout << "hello world" shift bits?) Point2 literally inhibits whatever innovation: something just invented isn't "well known", but me become as such in future. std::string use + not to "add". And they where not "well known" before STL had been invented.

@sbi 2012-04-09 10:16:07

@Emilio: These rules are for the common C++ developer. Of course they would prohibit creating anything like IO streams or spirit or, as I said above, even a decent string class. Read again, I preceded this with "Sometimes people have deviated from them and the outcome was not bad code, but such positive deviations are few and far between." IOW: When you are a beginner, strictly stick to those rules. When you are an experienced C++ developer (that's after several years), you might form your own opinion. When you deviate as far as, say, spirit does, rely on peer reviews to judge your ideas.

@sbi 2012-04-09 10:16:52

@curiousguy: Why? What could it do but compare containers, element by element, for equality? Isn't that obvious?

@Emilio Garavaglia 2012-04-09 16:57:00

@sbi: "peer review" is always a good idea. To me a badly choosen operator is not different from a badly choosen function name (I saw many). Operator are just functions. No more no less. Rules are just the same. And to understand if an idea is good, the best way is understand how long does it takes to be understood. (Hence, peer review is a must, but peers must be chosen between people free from dogmas and prejudice.)

@sbi 2012-04-09 18:02:59

@Emilio: I have no idea what this is arguing for or against. Are you sure you were replying to my comment?

@curiousguy 2012-04-09 20:15:01

@sbi "Isn't that obvious?" It isn't obvious to me that two containers should compare equal even if they aren't equivalents.

@sbi 2012-04-09 20:42:42

@curiousguy: That's the Java/C# approach. In C++, containers hold values, rather than references, so the difference between "equality" and "equivalence" is moot. (If I got the difference right, that is.)

@curiousguy 2012-04-10 00:49:11

@sbi To me, the only absolutely obvious and indisputable fact about operator== is that it should be an equivalence relation (IOW, you should not use non signaling NaN). There are many useful equivalence relations on containers. What does equality means? "a equals b" means that a and b have the same mathematical value. The concept of mathematical value of a (non-NaN) float is clear, but the mathematical value of a container can have many distinct (type recursive) useful definitions. The strongest definition of equality is "they are the same objects", and it is useless.

@curiousguy 2012-04-10 00:55:03

(...) The second strongest definition is "holds the same objects", and it is useless for value containers. Another strong definition is "two objects are equal iff they cannot be distinguished using their public interface" (comparison of addresses isn't "part of the public interface"). This relates to simulation and bi-simulation. The nuances with this definition comes with the parts of the interface you are allowed to use.

@curiousguy 2012-04-10 00:59:19

(...) Are the two set<int,function<bool(int,int)>> ({1},<) and ({1},>) equal? They have the same elements, but 1) if you can "compare" their comparator, you will be able to distinguish them; 2) if you add another element 2, their elements as a sequence won't be the same. Are two hash_set<int> with the same elements in a different order equal? Neither of these questions are absolutely obvious (at least to me).

@curiousguy 2012-04-10 01:08:06

(...) Also, what should operator= (x) do? Should it be equivalent with copy construction? Should it be equivalent with assign(x.begin(),x.end())? Both are very reasonable choices. I feel that there are strong arguments for both. This seems to argue against providing this operator at all.

@Emilio Garavaglia 2012-04-10 06:18:49

@sbi: It's conceptually against, but recognizes a good point. Essentially I don't believe in a difference between operators and functions: if + for "concatenation" or unary* for "keen star" or ~for "orthogonal" or "transposed" can be questionable, std::string::empty is also questionable (an imperative verb used to check a state ?!? Wouldn't it be is_empty better?). (...)

@Emilio Garavaglia 2012-04-10 06:22:02

(...) In any case, wherever you define a symbolic name, you define a convention between that name and what it represent. This convention cannot be obvious to anyone but you, until you don't expose enough "information" (in "information theory" sense) to your users (may be a comment, a document or a trivial use case, or the raw source code- when very simple). But I must see a clean contradiction (and may be even a "clutural racism" -note the quotes- in the background: saying "When you are a beginner, strictly stick to those rules", will defeat any geniality to emerge. (...)

@Emilio Garavaglia 2012-04-10 06:22:56

(...) The real fact is that, when you are a beginner the first sample of overloading yopu see is cout << "hello world", that is just a violation to the rules (<< should shift bits!) that is hidden by teacher lies presenting it a the "insertion operator". Now 1 only can be true: 1) the "insertion operator" is a lye, and is a violation to the rules thaught to the very first lesson about rules (LOL!) or ... 2) << is just a symbol whose meaning depends top what it is applied to, and hence no prejudice should exist about its meaning. (...)

@Emilio Garavaglia 2012-04-10 06:30:43

(...) The "insertion operator" is for stream and the shift operator for integers. The both have incidentally the same aspect. For this reason I always teach about << as "double left arrow" and + about "crosss". Whether "cross" becomes "add" or "concat", or "merge" etc., is something I have to teach when talking about the type it is related. Sorry to anyone for the very long comment.

@sbi 2012-04-10 07:14:34

@curiousguy: No, you are making this way to complicated. The obvious implementation for operator==() on a heterogeneous container (aka struct) is that, for all of its elements (aka "members"), operator==() returns true when applied to the corresponding element in another struct of the same type. The obvious meaning for operator==() of a non-heterogeneous container is that, for all elements in the container, operator==() returns true when applied to the corresponding object in another container of the same type.

@sbi 2012-04-10 07:28:41

@Emilio: I have allowed for violations of the rules, and I have listed IO streams and strings (and spirit) as obvious examples of those violations being successful. But that doesn't mean that a C++ newbie thinking overloading ! for strings might be a neat idea has it right. IO streams were designed ~30 years ago, when operator overloading was the newest thing in C++, brings a lot of historical weight, and, as you pointed out, newbies will usually learn the meaning of << as output operator before its meaning as a shift operator.

@sbi 2012-04-10 07:31:00

@Emilio: std::string, despite all its shortcomings, unified the C++ world which was split into thousands of different string classes. That alone was a great deed, and the designers would have been hard-pressed to do anything else so wrong for it to not be seen as a success — despite the fact that some disagreed with its (ab)use of + for concatenation.

@sbi 2012-04-10 07:32:15

@Emilio: And spirit deliberately set out to abuse operator overloading in order to create an embedded domain-specific language. That's not necessarily the first thing a newbie does, it might well be one of the most often legitimate reasons to abuse a programming language, and a very hard task to succeed with unless you have the backup of a strong community.

@Emilio Garavaglia 2012-04-10 07:45:08

@sbi: Your all arguments reduce to "don't do unless somebody else already did it a number of times". Apply this to "make children" and to "anyone", and humanity will extinguish in one generation time! It's a hard dirty work, but someone has to begin. Newbie or experts, is not the point. The idea is the point. If there is enough "believers" the idea goes, otherwise will die. Don't be "racist" against newbies: instead to tell them to "go away from water", teach them "how to swim"! (You may be surprised!)

@sbi 2012-04-10 07:55:11

@Emilio: Yes, my suggestion to those seeking advice is to not to invent something new. In the last 20 years, I have seen a lot of abuse of operator overloading, and very little justified use. (And I have been guilty of this, too, in my first few years of C++.) Consequently, my advice is to stick to well-known paradigms, unless you know enough of operator overloading that you wouldn't need advice in the first place. (As for the rest of your argument: The comparisons fall so awkwardly short, I won't spend time on them.)

@Tim Post 2012-04-10 07:57:09

Please take extended discussions to Stack Overflow Chat, in particular this room

@curiousguy 2012-04-10 08:39:08

@sbi So, are you trying to say that operator== for containers is ill-specified, or are you just saying it without actually trying to say that?

@curiousguy 2012-04-10 08:43:17

@sbi "In the last 20 years, I have seen a lot of abuse of operator overloading, and very little justified use." What kind of abuses have you seen? Mostly subtle abuses, or ridiculous abuses?

@Ben Voigt 2012-06-27 22:01:05

@curiousguy: operator= on std::auto_ptr comes to mind.

@curiousguy 2012-06-27 22:18:26

@BenVoigt after x = y; the value/state of x is equal to/equivalent with the value/state of y before, so it is not totally crazy. Also, the C++ language allows both C(const C&) and C(C&) as copy-ctor signatures, and operator=(const C&) as well as operator=(C&) for assignment operator signature, so the core language quite explicitly supported this design too.

@Ben Voigt 2012-06-27 22:40:12

@curiousguy: The language allows defining operator+ as subtraction also. It's a very VERY bad idea, because it's surprising. x = y; should not change y. It does not do so for any built-in type. Support for C::operator=(C&) is needed to support things like reference-counted pointers, where internal state may change but the user-visible state does. std::auto_ptr is universally recognized as a mistake.

@curiousguy 2012-06-27 23:07:52

@BenVoigt "The language allows defining operator+ as subtraction also." actually the code language doesn't know addition from subtraction, so it couldn't tell. OTOH, the core language knows quite well what a copy ctor means. "Support for C::operator=(C&) is needed to support things like reference-counted pointers, where internal state may change but the user-visible state does." No it is not.

@Edward Falk 2013-04-12 17:17:38

Yeah, I agree that cout << "Hello world" is the worst violation of these rules. I'm convinced that it was implemented as a demonstration of what operator overloading could do, and we never intended to become used in the real world.

@Sekory 2015-02-24 19:42:45

Why did you write that Comparison operators should be implemented as non-member functions? What is the reason?

@sbi 2015-02-26 08:39:25

@Sekory: Did I even write this in this answer? Anyway, it's explained here: If a binary operator treats both operands equally (it leaves them unchanged), implement this operator as a non-member function. What exactly do you want to know.

@Robinson 2015-06-08 10:52:05

With respect to "whenever the meaning of an operator is not obviously clear and undisputed, it should not be overloaded", would overloading < and > for a vector class comparing length violate this principle?

@sbi 2015-06-08 11:54:50

@Robinson: The STL defines comparison of containers as lexicographical comparison, not as length. Therefore, everybody looking at v1 < v2 would expect it to do so, too. For what you want, there's v1.size() < v2.size().

@Moiz Sajid 2015-08-30 11:30:54

The assignment operator is overloaded by default, right?

@sbi 2015-08-30 13:24:19

@Moiz: In case you want to know whether the compiler generates an assignment operator by default, see this question and its answer.

@Justin Time 2016-02-02 19:58:47

Tying into these rules, I would personally say that the best reason to overload an operator is to provide consistency with similar classes. If you're making a math-related class, for instance, it would be reasonable to overload assignment, arithmetic, and comparison operators for use with said class, conversion operators to convert to built-in and/or standard math types, and I/O operators; not so much array, new/delete, or pointer-like operators. Conversely, if you're making a video game character class, it's unreasonable to overload arithmetic operators to modify the character's level.

@Daniel H 2017-06-27 21:02:51

How would you feel about operator| for piping, such as in range adaptors?

@sbi 2017-07-05 15:37:15

@Daniel: Look, if nobody had come up with overloading << and >> for IO, and you came up with it now, it would be frowned upon. Since it's been done 30 years ago, it's part of the domain now. The same goes for everything else that's not in common use: If you or I do it in our projects, it's rather likely our co-workers will complain. If it is done in a popular boost library, and fits the domain of the code (using | for piping is well-known), this might be different.

Related Questions

Sponsored Content

21 Answered Questions

[SOLVED] What is the "-->" operator in C++?

5 Answered Questions

[SOLVED] Undefined behavior and sequence points

21 Answered Questions

18 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

5 Answered Questions

[SOLVED] Iterator invalidation rules

35 Answered Questions

[SOLVED] What is the !! (not not) operator in JavaScript?

  • 2009-04-24 08:13:58
  • Hexagon Theory
  • 469505 View
  • 2730 Score
  • 35 Answer
  • Tags:   javascript operators

8 Answered Questions

[SOLVED] What is The Rule of Three?

6 Answered Questions

[SOLVED] How does the compilation/linking process work?

5 Answered Questions

[SOLVED] What is the copy-and-swap idiom?

Sponsored Content