Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading the operator ->

I was looking at overloading the -> operator. I came up with the following simple example:

struct foo
{
    int p = 12;
};

struct A
{    
    foo* f;
    A()
    {
        this->f = new foo();
    }
    foo* operator-> ()
    {
        return f;
    }
};

int main()
{
    A a;
    std::cout << a->p; //output 12
}

Although this example works, yet I am hoping if someone could tell me why it works. I was thinking that it should work like this

std::cout << a->->p; //The first arrow returns the pointer 
                     //the second arrow dereferences it

but here it seems like a single arrow not only returns the pointer but it also dereferences it. Is this a special case in C++?

like image 853
MistyD Avatar asked Aug 23 '20 01:08

MistyD


1 Answers

Yes, this is by-design, operator-> will be called recursively on the return value; then we can use such class (so-called smart pointers) in the same way as raw pointers.

If a user-defined operator-> is provided, the operator-> is called again on the value that it returns, recursively, until an operator-> is reached that returns a plain pointer. After that, built-in semantics are applied to that pointer.

like image 82
songyuanyao Avatar answered Sep 26 '22 02:09

songyuanyao