Operator Overloading for Member Functions

◀ Operator Overloading▶ Operator Overloading for Non-Member Functions
Amazon Let’s first learn how to compose overloaded functions in a class. Suppose we have a class Complex that represents mathematical complex numbers. Say you want to overload operators that define relations between two complex numbers, which include addition, subtraction, multiplication, and conjugation.

For addition, you want to add two complex numbers and return the result to the invoking object. You can do the following:
Complex operator+(Complex & c); /* inside class Complex */
Complex Complex::operator+(Complex & c) { /* definition */ … return … }
Inside main(), let’s say a, b, c are all instances of Complex. The following two lines mean the same thing:
a = b.operator+(c);
a = b + c;
The second assignment is a unique property of operators such as +, -, *, and /. It allows programmers to use operator notations so that they look friendlier.

As you can see, you cannot make the functions void because you need to return the result for the assignment operator to work.

An important point to note is that you can also do this:
a = a + b + c;
That’s because the compiler sees the expression as a = (a + b) + c and evaluates a + b first. Then the result replaces a + b, turning the expression into a = result + c. This is analogous to cout’s ability to do cout << … << …

On the other hand, let’s say you want addition to work between a Complex object and an int, you can do the following:
Complex operator+(int n); /* inside class Complex */
Complex Complex::operator+(int n) { /* definition */ … return … }
But now you only can do
a = b + 5;
and not
a = 5 + b;
The compiler views expression a = b + 5 as equivalent to a = b.operator+(5), and won’t recognize a = 5.operator+(b).

Next I will show you how you can make a = 5 + b work in a non-member overloaded function!
◀ Operator Overloading▶ Operator Overloading for Non-Member Functions

fShare
Questions? Let me know!