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 Modifier

As yet another example, we'll look at conjugate, which is a modifier function that transforms a Complex number into its complex conjugate. The complex conjugate of x + yi is x - yi.

As a nonmember function, this looks like:

  void conjugate (Complex& c) {
    c.imag = -c.imag;
  }

As a member function, it looks like

  void conjugate () {
    imag = -imag;
  }

By now you should be getting the sense that converting a function from one kind to another is a mechanical process. With a little practice, you will be able to do it without giving it much thought, which is good because you should not be constrained to writing one kind of function or the other. You should be equally familiar with both so that you can choose whichever one seems most appropriate for the operation you are writing.

For example, I think that Add should be written as a nonmember function because it is a symmetric operation of two operands, and it makes sense for both operands to appear as parameters. It just seems odd to invoke the function on one of the operands and pass the other as an argument. (Actually, in the next section you'll learn of a method called operator overloading which eliminates the need for explicitly calling functions like Add.)

On the other hand, simple operations that apply to a single object can be written most concisely as member functions (even if they take some additional arguments).


Last Update: 2005-11-21