Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What legitimate reasons exist to overload the unary operator&?

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....)

like image 884
Billy ONeal Avatar asked Jun 27 '11 16:06

Billy ONeal


People also ask

How unary operators are overloaded?

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.

Why would you want to overload an operator?

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.

What are the advantages of operator overloading in C++?

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.

What is operator overloading explain unary operator overloading using member function?

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.


2 Answers

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:

  • You have an object which is masquerading as some other object.
  • This object can obtain a pointer to the thing it's masquerading as.

Returning anything other than a legitimate pointer would violate the principle of least astonishment.

like image 84
Mark Ransom Avatar answered Oct 21 '22 17:10

Mark Ransom


It is useful when representing the & operation in lambda placeholder notation, e.g. &_1[_2].

like image 36
user541686 Avatar answered Oct 21 '22 17:10

user541686