The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Another Function on Complex Numbers

Another operation we might want to perform on complex numbers is addition. You can add complex numbers by adding the real parts and adding the imaginary parts. Written as a nonmember function, that looks like:

  Complex Add (Complex& a, Complex& b) {
    return Complex (a.real + b.real, a.imag + b.imag);

To invoke this function, we would pass both operands as arguments:

    Complex sum = Add (x, y);

Written as a member function, it would take only one argument, which it would add to the current object:

  Complex Add (Complex& b) {
    return Complex (real + b.real, imag + b.imag);

Again, we can refer to the instance variables of the current object implicitly, but to refer to the instance variables of b we have to name b explicitly using dot notation. To invoke this function, you invoke it on one of the operands and pass the other as an argument.

    Complex sum = x.Add (y);

From these examples you can see that the current object (this) can take the place of one of the parameters. For this reason, the current object is sometimes called an implicit parameter.

Last Update: 2005-12-05