0

As far as I understand the -> operator dereferences then accesses the members of a pointer to a class object.

identifier->member is effectively the equivalent to using: (*identifier).member

Consider the following: compiled and tested, functions as expected

#include <iostream>

class A
{
public:
    int x{0};
};

class A_Abstraction
{
public:
    A *ptrToA;
    A_Abstraction() : ptrToA{new A} {};a
    A *operator->() { return ptrToA; }
};

int main()
{
    A_Abstraction a;
    a->x = 10;
    std::cout << a->x << '\n';
}

In my basic understanding the A_Abstraction::operator->() would resolve to a A*, which would still require both dereferencing and the use of a member access operator. So wouldn't accessing A::x through A_Abstraction::operator->() require something like this: a->->x

Obviously it doesn't and the code compiles and runs as expected. How does the compiler manage this?

wigi426
  • 91
  • 4
  • @VolkanÜnal yes it does very much, thank you. Should I delete my post or link that post in an edit? – wigi426 Nov 04 '22 at 14:45
  • [member access operators](https://en.cppreference.com/w/cpp/language/operator_member_access#Built-in_member_access_operators) _"...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...."_ – Richard Critten Nov 04 '22 at 15:00

1 Answers1

0

You are right that it resolves to A* and it needs dereferencing. However, that dereferencing is handled by (unary) operator*(), not operator->().

As for accessing, while the return type is A*, you'll only get that if you call it manually (like a.operator->()). If you write a->x, that's interpreted as (*(a.operator->())).x (extra parentheses added to clarify the precedence). Therefore, you can't write a->->x.

lorro
  • 10,687
  • 23
  • 36
  • 1
    Thank you, however I've closed the post now as my question was effectively answered elsewhere. – wigi426 Nov 04 '22 at 14:46