How to overload the binary operators in C++

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2016/11/overload-binary-operators-c/

Operator overloading is syntactic sugar, and is used because it allows programming using notation nearer to the target domain[1] and allows user-defined types a similar level of syntactic support as types built into a language. It is common, for example, in scientific computing, where it allows computing representations of mathematical objects to be manipulated with the same syntax as on paper.

Operator overloading does not change the expressive power of a language (with functions), as it can be emulated using function calls. For example, consider variables a, b, c of some user-defined type, such as matrices:

a + b * c

In a language that supports operator overloading, and with the usual assumption that the ‘*’ operator has higher precedence than ‘+’ operator, this is a concise way of writing:

add (a, multiply (b,c))

However, the former syntax reflects common mathematical usage.

As unary operators can be overloaded, we can also overload binary operators. Syntax for overloading a binary operator using a member function is as follows:

 

Syntax for overloading a binary operator using a friend function is as follows:

 

Following program demonstrates overloading the binary operator + using a member function:

 

Following program demonstrates overloading the binary operator + using a friend function:

 

Note: Operators such as =, ( ), [ ], and -> cannot be overloaded using friend functions.

Take your time to comment on this article.

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2016/11/overload-binary-operators-c/

Add a Comment

Your email address will not be published. Required fields are marked *

Like the article? please consider sharing it. Thank you

Advertisment ad adsense adlogger