Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are operators sometimes stand-alone and sometimes class methods?

Why is that sometimes an operator override is defined as a method in the class, like

MyClass& MyClass::operatorFoo(MyClass& other) { .... return this; };

and sometimes it's a separate function, like

MyClass& operatorFoo(MyClass& first, MyClass& bar)

Are they equivalent? What rules govern when you do it one way and when you do it the other?

like image 206
Paul Tomblin Avatar asked Dec 07 '09 19:12

Paul Tomblin


People also ask

What is the purpose of using operator?

An operator is used to manipulate individual data items and return a result. These items are called operands or arguments. Operators are represented by special characters or by keywords.

Why operator overloading is not possible in Java?

Java doesn't allow user defined operator overloading because if you allow programmer to do operator overloading they will come up with multiple meanings for same operator which will make the learning curve of any developer hard and things more confusing and messing.

Is operator overriding possible?

Operator Overloading in C++ In C++, we can make operators work for user-defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.

What operators Cannot be overloaded in C++?

You cannot overload the following operators: . You cannot overload the preprocessor symbols # and ## . An operator function can be either a nonstatic member function, or a nonmember function with at least one parameter that has class, reference to class, enumeration, or reference to enumeration type.


1 Answers

If you want to be able to do something like 3 + obj you have to define a free (non-member) operator.

If you want to make your operators protected or private, you have to make them methods.

Some operators cannot be free functions, e.g., operator->.

This is already answered here:

difference between global operator and member operator

like image 88
Tim Sylvester Avatar answered Sep 27 '22 21:09

Tim Sylvester