Ahmed A
Ahmed A

Reputation: 3652

overloading operator -> to access data member

I have a question about the following sample program about overloading -> operator, same across in a C++ tutorial:

 5     class myclass
 6     {
 7         public:
 8         int i;
 9
10         myclass *operator->()
11         {return this;}
12     };
13
14     int main()
15     {
16         myclass ob;
17
18         ob->i = 10;
19         cout << ob.i << " " << ob->i << endl;
20
21         return 0;
22     }

$ ./a.out
10 10

I am trying to understand how line 18 works. I understand that "ob" is not a pointer, but since "class myclass" has defined the operator "->", "ob->i" is valid (syntactically), so far good. However, "ob->" returns a pointer, and I don't see how it is de-referenced to get access to member "i" and setting it.

I am assuming the above explanation will also explain how in line 19 "ob->i" is printed as an int.

Thank you, Ahmed.

Upvotes: 2

Views: 85

Answers (2)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506847

x->y is equivalent to x.operator->()->y if x is a class object and an overloaded member operator-> is found.

I hope it gets clearer from that.

Upvotes: 6

Luchian Grigore
Luchian Grigore

Reputation: 258558

operator-> gets called in a chain until it can no longer get called - in your case, it's actually called twice - once, the overloaded operator on your object, which returns a pointer, and the second time, the built-in operator which dereferences that pointer and accesses that member.

Upvotes: 7

Related Questions