It was mentioned on stack overflow by a programmer that if you declare one class function, for example:
operator++()
That for user-interface purposes (as the user naturally assumes its opposite should work), you should declare the other:
operator--()
Is there a link to an article that supports this? I wish to be able to reference it to other programmers.
I thought to add that, perhaps the suggestion is similar to the rule of 3, or the big 2.
In light of hostilefork’s answer, perhaps the opposite functions should be declared even in instances where even it doesn’t serve a purpose, but as private, so the user explicitly knows they cannot call that function? Or is that just being pedantic?
One hard thing about C++ and operator overloading is that it can be sort of a pun. Overloading assignment created a bit of a pickle with
auto_ptr, because code that tried to take “assignment” for granted was being surprised by assigning A to B and then finding immediately afterward that A != B.http://hostilefork.com/2009/07/10/smart-pointer-casting-study/
I’ll point out if the following generalized code will compile, the users of a class will often assume it wouldn’t assert:
There’s no law enforcing that, though. Some people are vocal about it being bad to be tolerating such a a semantic free-for-all:
http://yosefk.com/c++fqa/operator.html
I’d lean toward saying it’s important to maintain some of those expectations. But there’s nothing wrong with not compiling a program where decrementing shouldn’t have meaning. Forward iterator was mentioned, perfect example.
The foundational things that you get with languages tend to be very “mathematical” and “symmetric” (like an integer is unlikely to have addition but not subtraction). But I think that classes that are being tailored to solve specific problems trend toward getting greater value from being asymmetrical.
It’s sort of the generality-vs-specificity thing. Think about an application that’s close to the user. They don’t want all things to be equally accessible…more common operations should be “easy” while infrequent operations can be marginalized a bit. Some of the most frustrating software is that which isn’t focused on the common case. Specialized classes that are there to solve a problem are often going to be a lot less symmetrical than General Purpose Language constructs or libraries.