Okay, I've been inspired to do some head punching. Seems like overloading operator&
leads to not a small amount of pain.
What legitimate cases exist for overloading it?
(Can't say I've ever done that....)
Overloading Unary Operator: Let us consider to overload (-) unary operator. In unary operator function, no arguments should be passed. It works only with one class objects. It is a overloading of an operator operating on a single operand.
Operator overloading facilitates the specification of user-defined implementation for operations wherein one or both operands are of user-defined class or structure type. This helps user-defined types to behave much like the fundamental primitive data types.
Operator overloading is one of the best features of C++. By overloading the operators, we can give additional meaning to the operators like +-*/=.,= etc., which by default are supposed to work only on standard data types like int, float, char, void etc.
Unary operator acts on one operand only. In case overloaded operator function is a class member function, then it will act on the object with which it is called and use it as operand. Hence we need not to pass any extra argument in unary operator function if its class member function.
I seem to remember something like a smart pointer class which overrode operator&
because it wanted to return the address of the contained pointer rather than the address of the smart pointer object. Can't remember where I saw it or whether it seemed like a good idea at the time.
Aha, remembered: Microsoft's CComPtr.
Edit: To generalize, it might make sense under the following conditions:
Returning anything other than a legitimate pointer would violate the principle of least astonishment.
It is useful when representing the &
operation in lambda placeholder notation, e.g. &_1[_2]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With