next up previous
Next: Overloading operators Up: Simple Classes: mycomplex0.h Previous: Constructors

Functions acting on classes

Next we introduce a function cadd for adding two complex numbers.

#include <iostream>

class complex {
  double re;
  double im;

  // Constructors
  complex(){re = 0; im = 0;}
  complex(double r, double i = 0){re = r; im = i;}

complex cadd(complex &z1, complex &z2)
  return complex( +, +;

int main(){
   complex a, b, sum;

   cout << "Enter Re(a) and Im(a)\n";
   cin >> >>;
   cout << "Enter Re(b) and Im(b)\n";
   cin >> >>;
   sum = cadd(a, b);
   cout << "a + b is " << << " + I * " << << "\n";

Notice that the function cadd is defined outside the class definition. So it is not a class method. It just operates on complex objects just as the math library function sqrt operates on double precision numbers. Here, the function cadd takes two complex variables as arguments. They are declared as references. Passing pointers or references is customary for arguments that are not simple base types. For large classes this practice is more efficient. The function return type is complex. The return statement that generates the return value uses the complex constructor with two arguments. Those arguments are themselves expressions. The expressions specify how the two complex numbers are added, namely by adding separately their real and imaginary parts.

The function is invoked in the main program in the usual way and the result is stored in the variable sum.

Carleton DeTar 2017-02-13