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.


Accessor Functions

By convention, accessor functions have names that begin with get and end with the name of the instance variable they fetch. The return type, naturally, is the type of the corresponding instance variable.

In this case, the accessor functions give us an opportunity to make sure that the value of the variable is valid before we return it. Here's what getReal looks like:

double Complex::getReal ()
{
  if (cartesian == false) calculateCartesian ();
  return real;
}

If the cartesian flag is true then real contains valid data, and we can just return it. Otherwise, we have to call calculateCartesian to convert from polar coordinates to Cartesian coordinates:

void Complex::calculateCartesian ()
{
  real = mag * cos (theta);
  imag = mag * sin (theta);
  cartesian = true;
}

Assuming that the polar coordinates are valid, we can calculate the Cartesian coordinates using the formulas from the previous section. Then we set the cartesian flag, indicating that real and imag now contain valid data.

As an exercise, write a corresponding function called calculatePolar and then write getMag and getTheta. One unusual thing about these accessor functions is that they are not const, because invoking them might modify the instance variables.


Last Update: 2005-12-05