Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 498
Ferruccio Avatar asked Feb 06 '09 11:02

Ferruccio


People also ask

Why operator overloading is not possible in C?

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.

Is it possible to overload operator?

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.

Which operator we Cannot overload 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.

Why is it necessary to overload an operator in C?

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.


1 Answers

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

like image 73
Anton Gogolev Avatar answered Sep 22 '22 17:09

Anton Gogolev