3

So I think I might be overthinking this but I wanted to know if someone could clarify why the following statement works in the given code

f->hello();

This is the code

struct bar
{
    void hello()
    {
        std::cout << "Hello World";
    }
};

struct foo
{
    bar* f;
    foo() {
        f = new bar();
    }

    ~foo() {
        delete f;
    }

    bar* operator->() {
        return f;
    }
};

int main()
{
    foo f;
    f->hello(); //Works
}

Since the following code from above returns a pointer

bar* operator->() {
        return f;
    }

should'nt

f->hello(); actually be f->->hello();

why does f->hello() work and f->->hello() fails ? The reason i am thinking that f->->hello() should work is because

f->ptrReturned->hello();

If we overload the -> operator are we required to return a ptr type ? Form what I have tried it seems returning an object type is not allowed

2
  • ->-> is not a correct syntax. f->hello() is handled by the compiler. Commented Jul 29, 2018 at 3:45
  • Yeah, the compiler fudges this and re-applies the -> operator to the returned pointer so you don't have the awkward syntax problems. Commented Jul 29, 2018 at 4:04

2 Answers 2

1

Your understanding is correct basically, but ->-> is not valid syntax. You can use the overloaded operator-> like

f.operator->()->hello();
//^^^^^^^^^^^^          return the pointer
//            ^^^^^^^^^ call hello() on the returned pointer

f->hello() is treated as the same of f.operator->()->hello(); that makes the usage of class with overloaded operator-> (e.g. smart pointers) consistent with built-in pointers. The usage would be more natural, and could be used with raw pointers in more general context like templates.

And,

If we overload the -> operator are we required to return a ptr type ?

There're some restrictions:

The overload of operator -> must either return a raw pointer, or return an object (by reference or by value) for which operator -> is in turn overloaded.

Sign up to request clarification or add additional context in comments.

Comments

1

Apparently, that's just how an overloaded operator-> works. The part before the -> (not including the operator itself) gets replaced with the return value of the overloaded operator. For example, std::unique_ptr::operator-> returns a pointer, which then gets dereferenced by the ->.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.