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:
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.
Write your implementation of calculatePolar in the commented area of the active code below. Once youβre done with that, write the getMag and getTheta accessor functions. Read the comments in main to see how weβll test if your functions works. If you get stuck, you can reveal the hint below for help.