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

Ferruccio picture Ferruccio · Feb 6, 2009 · Viewed 31k times · Source

It would be very useful to be able to overload the . operator in C++ and return a reference to an object.

You can overload operator-> and operator* but not operator.

Is there a technical reason for this?

Answer

Anton Gogolev picture Anton Gogolev · Feb 6, 2009

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++.