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.


A Function on Complex Numbers

Let's look at some of the operations we might want to perform on complex numbers. The absolute value of a complex number is defined to be sqrt(x2 + y2). The abs function is a pure function that computes the absolute value. Written as a nonmember function, it looks like this:

  // nonmember function
  double abs (Complex c) {
    return sqrt (c.real * c.real + c.imag * c.imag);
  }

This version of abs calculates the absolute value of c, the Complex object it receives as a parameter. The next version of abs is a member function; it calculates the absolute value of the current object (the object the function was invoked on). Thus, it does not receive any parameters:

class Complex
{
private:
  double real, image;

public:
  // ...constructors

  // member function
  double abs () {
    return sqrt (real*real + imag*imag);
  }
};

I removed the unnecessary parameter to indicate that this is a member function. Inside the function, I can refer to the instance variables real and imag by name without having to specify an object. C++ knows implicitly that I am referring to the instance variables of the current object. If I wanted to make it explicit, I could have used the keyword this:

class Complex
{
private:
  double real, image;

public:
  // ...constructors

  // member function
  double abs () {
    return sqrt (this->real * this->real + this->imag * this->imag);
  }
};

But that would be longer and not really any clearer. To invoke this function, we invoke it on an object, for example

    Complex y (3.0, 4.0);
    double result = y.abs ();


Last Update: 2005-12-05