I have hard time understanding the explanation from stroustrup for what difficulties one must have faced, if operator overloading for '.' was allowed.
See this quote from Bjarne Stroustrup:
Operator . (dot) could in principle be overloaded using the same technique as used for ->. However, doing so can lead to questions about whether an operation is meant for the object overloading . or an object referred to by . For example:
class Y { public: void f(); // ... }; class X { // assume that you can overload . Y* p; Y& operator.() { return *p; } void f(); // ... }; void g(X& x) { x.f(); // X::f or Y::f or error? }
In the above example why should there be any confusion while executing x.f()
?
Y& operator.() { return *p; }
Here is what i think:
- operator.() is called on x hence isnt it obivous and intuitive that
Y& operator.()( return *p; }
should be called ? - Upon returning
*p
which points to object of type Y and henceY::f()
should be called finally ( notX::f()
)
What am i missing in stroustup's explanation? Why is it not straightforward?