Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would anyone want to overload the & (address-of) operator? [duplicate]

Tags:

Possible Duplicate:
What legitimate reasons exist to overload the unary operator& ?

I just read this question, and I can't help but wonder:

Why would anyone possibly want to overload the & ("address-of") operator?

SomeClass* operator&() const {     return address_of_object; } 

Is there any legitimate use case?

like image 741
Tony the Pony Avatar asked Jun 27 '11 22:06

Tony the Pony


People also ask

What is the need of overloading operators write down the program to overload unary operators in C ++?

This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.

Can we overload [] operator?

where () is the function call operator and [] is the subscript operator. You cannot overload the following operators: .

How do you overload an operator?

To overload an operator, we use a special operator function. We define the function inside the class or structure whose objects/variables we want the overloaded operator to work with.

Can you overload the operator for data type int?

No we cannot overload integer or float types because overloading means to change the working of existing operators or make them to work with objects int is single member not an object.


2 Answers

If you're dealing with any sort of wrapper objects, you might want or need to transparently forward the access to the wrapper to the contained object. In that case, you can't return a pointer to the wrapper, but need to overload the address-of operator to return a pointer to the contained object.

like image 99
Timo Geusch Avatar answered Oct 18 '22 17:10

Timo Geusch


Because they're evil and want you to suffer.

Or I guess if you are using proxy objects? I suppose you might want to return a pointer to the managed object instead of the container - although i'd rather do that with a getter function. Otherwise you'd have to remember to use things like boost::addressof.

like image 45
Node Avatar answered Oct 18 '22 17:10

Node