Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading unary operator &

Let's consider a class with overloaded unary operator & (Address-of). Let it be class A

template <class C>
class A
{
public:
    C * operator &()
    {
        return &data;
    }
    //...
private:
    C data;
}

Now I want to pass to some function a pointer of type A to fill its data. Let us call it f

void f(A * auto_containter)
{
    //...
}

But it is clear why the code bellow wouldn't work (even wouldn't compile). It is because the overloaded operator is called.

A a;
f(&a);

The question is following:

Is there any syntax to pass address of a to f? If no, then for me it is very strange why it is allowed to overload unary operator &, because it makes code more buggy and difficult to understand. Or there are some other reasons?

like image 975
Mihran Hovsepyan Avatar asked Jun 20 '11 11:06

Mihran Hovsepyan


People also ask

What is overloading unary operator?

You overload a unary operator with either a nonstatic member function that has no parameters, or a nonmember function that has one parameter. Suppose a unary operator @ is called with the statement @t , where t is an object of type T .

What is unary operator in C++?

Unary operators: are operators that act upon a single operand to produce a new value. Types of unary operators: unary minus(-) increment(++) decrement(- -)

What is unary operator example?

In mathematics, an unary operation is an operation with only one operand, i.e. a single input. This is in contrast to binary operations, which use two operands. An example is any function f : A → A, where A is a set.

What is operator overloading explain with example?

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


2 Answers

Is there any syntax to pass address of a to f?

Yes, there's ugly syntax:

f( reinterpret_cast<A*>( &reinterpret_cast<char&>(a) ) );

boost::addressof is a nice and generic wrapper around it.

like image 129
Kirill V. Lyadvinsky Avatar answered Oct 12 '22 00:10

Kirill V. Lyadvinsky


Use std::addressof function(or boost::addressof pre C++11). In any case, overloading unary & is highly dubious. Why do it instead of having a named function that returns the address of your data?

like image 45
Armen Tsirunyan Avatar answered Oct 12 '22 01:10

Armen Tsirunyan