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?
Function overloading is a feature of Object Oriented programming languages like Java and C++. As we know, C is not an Object Oriented programming language. Therefore, C does not support function overloading.
These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator.
Rules of operator overloading We can overload an operator as its type only i.e., a unary operator cannot be overloaded as a binary operator and vice versa. We can't overload operators that are not a part of C++. We can perform operator overloading only in user-defined classes.
The purpose of operator overloading is to provide a special meaning of an operator for a user-defined data type. With the help of operator overloading, you can redefine the majority of the C++ operators. You can also use operator overloading to perform different operations using one operator.
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++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With