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?
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?
Stroutstrup has an answer for this question:
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 D&E.
See here:
Member access (selection) operator (that's how .
is called) can in principle be overloaded using the same technique as used for ->
. However, this 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
{
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, but at the time of standardization it was not obvious which way would be best.
See The Design and Evolution of C++ for further details.
Stroustrup said C++ should be an extensible, but not mutable language.
The dot (attribute access) operator was seen as too close to the core of the language to allow overloading.
See The Design and Evolution of C++, page 242, section 11.5.2 Smart References.
When I decided to allow overloading of operator
->
, I naturally considered whether operator.
could be similarly overloaded.At the time, I considered the following arguments conclusive: If
obj
is a class object thenobj.m
has a meaning for every memberm
of that object's class. We try not to make the language mutable by redefining built-in operations (though that rule is violated for=
out of dire need, and for unary&
).If we allowed overloading of
.
for a classX
, we would be unable to access members ofX
by normal means; we would have to use a pointer and->
, but->
and&
might also have been re-defined. I wanted an extensible language, not a mutable one.These arguments are weighty, but not conclusive. In particular, in 1990 Jim Adcock proposed to allow overloading of operator
.
exactly the way operator->
is.
The "I" in this quote is Bjarne Stroustrup. You cannot be more authoritative than that.
If you want to really understand C++ (as in "why is it this way"), you should absolutely read this book.