Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inability to overload Dot '.' operator in c++

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:

  1. operator.() is called on x hence isn't it obvious and intuitive that Y& operator.()( return *p; } should be called ?
  2. Upon returning *p which points to object of type Y and hence Y::f() should be called finally ( not X::f() )

What am i missing in Stroustup's explanation? Why is it not straightforward?

like image 366
anurag86 Avatar asked Feb 12 '17 02:02

anurag86


1 Answers

There has been some progress: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf . Due to some technical problems this won't be in C++17, but I hope to see it for C++20.

like image 164
Bjarne Stroustrup Avatar answered Nov 15 '22 20:11

Bjarne Stroustrup