Why can’t you overload the ‘.’ operator in C++?

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?
}

This problem can be solved in several ways. At the time of
standardization, it was not obvious which way would be best. For more
details, see The Design and Evolution of C++.

Leave a Comment