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.


Invoking One Member Function from Another

As you might expect, it is legal and common to invoke one member function from another. For example, to normalize a complex number, you divide through (both parts) by the absolute value. It may not be obvious why this is useful, but it is.

Let's write the function normalize as a member function, and let's make it a modifier.

  void normalize () {
    double d = this->abs();
    real = real/d;
    imag = imag/d;
  }

The first line finds the absolute value of the current object by invoking abs on the current object. In this case I named the current object explicitly, but I could have left it out. If you invoke one member function within another, C++ assumes that you are invoking it on the current object.

As an exercise, rewrite normalize as a pure function. Then rewrite it as a nonmember function.


Last Update: 2005-12-05