Question:
Which arguments do you receive when you overload
.
and
-> , and what do you do with the arguments? I know that for overloading
[] you receive the index. How about
. and
-> ?
Answer:
First, the . operator cannot be overloaded. If it could be, there would be no way to access members of the object
directly.
Here are the rules for operator -> :
- Operator
-> must be defined as a member of a class.
- The operator takes a second argument but the type is unspecified.
- The return value must be a type for which operator
-> is meaningful.
Here is an example:
struct X
{
Y * operator ->() { return yPtr_; }
struct Y { void foo (); }
Y * pPtr;
}
X x; x->foo () ; // calls X::Y::foo
The operand to operator
-> (in this case foo) is applied to its return
value. If the return value is something for which
-> does not make sense,
that is an error.