Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overloading and precedence

In C# you can overload operators, e.g. + and *. In their mathematical interpretation, these operators have a well defined order of precedence.

Is this order kept when overloading, does it change in some deterministic way, or can you overload the order of precedence as well?

like image 867
olagjo Avatar asked Oct 17 '12 23:10

olagjo


People also ask

What is meant by operator overloading and operator precedence?

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 is the rule of precedence for operators?

Operators are listed in descending order of precedence. If several operators appear on the same line or in a group, they have equal precedence. All simple and compound-assignment operators have equal precedence. An expression can contain several operators with equal precedence.

Which has the highest precedence () or?

In Java, parentheses() and Array subscript[] have the highest precedence in Java. For example, Addition and Subtraction have higher precedence than the Left shift and Right shift operators.

What is operator precedence meaning?

In mathematics and computer programming, the order of operations (or operator precedence) is a collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given mathematical expression.


2 Answers

If you overload an operator, it will always take precedence over the default implementation. However, you can't change the precedence of the operator itself, so it will be kept as default. More information on MSDN.

Relevant quotes:

User-defined operator implementations always take precedence over predefined operator implementations: Only when no applicable user-defined operator implementations exist will the predefined operator implementations be considered.

and

User-defined operator declarations cannot modify the syntax, precedence, or associativity of an operator. For example, the / operator is always a binary operator, always has the precedence level specified in Section 7.2.1, and is always left-associative.

like image 186
keyboardP Avatar answered Oct 20 '22 19:10

keyboardP


Overloading does not change precedence.

Operator precedence is set by the compiler, and cannot be changed, at least not without customizing the compiler.

like image 42
Kendall Frey Avatar answered Oct 20 '22 17:10

Kendall Frey