Overloading the '+' Operator
We will overload the + operator such that it will add two Complex objects and return the result as a Complex object. As we have learned in the lectures on overloading C++ operators, the operator function for + can either be a member function or a non-member function. The lecture notes discuss in detail which approach is better under what circumstances. For the purpose of this lab, we will implement this operator function as a member function
The operator + is a binary operator (meaning it takes two
operands). The prototype of the operator function for
overloading the + operator when implemented as member function is:
const Complex operator+ (const Complex& rhs)
const;
The operator+ function is implemented in the following manner:
- If you are adding two Complex objects C1 and C2 to get
another Complex object (C3 = C1 + C2), C1 is the calling
object (this), and rhs refers to the right hand side (C2) of the
expression C1 + C2.
The statement:C3 = C1 + C2;
would invoke the operator+ function, and it is equivalent to
C3 = C1.operator+(C2) - The lhs or the left hand side (C1) is passed implicitly. Hence we need to pass only rhs explicitly. This is because we are implementing operator+ as a member function. If we would write it as non-member function, we would need to pass both lhs and rhs explicitly.
- Create a Complex object in this function (C3 in above example) and assign the addition of real parts of C1 and C2 to the real part of C3. Similarly, assign the addition of imaginary parts of C1 and C2 to imaginary part of C3.
- Return the object C3. Note that the return type is by const value.