Operator Overloading  « Prev  Next »

C++ Friend Function vs Member Function - Exercise

Objective

Write two add() functions for the matrix class: one as a friend nonmember function and one as a member function. Then explain the advantages of defining one over the other.

What you will build

Both functions should accept two matrices and return a new matrix where each element is the sum of the corresponding elements of the two inputs.

Instructions

  1. Implement a nonmember friend function with this declaration:
    friend matrix add(const matrix& m1, const matrix& m2);
  2. Implement a member function with this prototype:
    matrix matrix::add(const matrix& m);
  3. Include a short discussion comparing the two approaches (friend vs member): symmetry, access needs, implicit conversions, readability, and maintainability.

Matrix class (provided)

Use the following class definition and constructors/destructor as your base context:

class matrix {
public:
   matrix(int d);
   matrix(int d1, int d2);
   ~matrix();
   int ub1() const { return (s1 - 1); }
   int ub2() const { return (s2 - 1); }
private:
   int**   p;
   int     s1, s2;
};

matrix::matrix(int d): s1(d), s2(d){
   if (d < 1) {
      // cerr is the standard stream for error output
      // similar to stderr in C
      cerr << "illegal matrix size"
        << d << "by" << d << "\n";
      exit(1);
   }
   p = new int*[s1];
   for (int i = 0; i < s1; i++)
      p[i] = new int[s2];
}
matrix::matrix(int d1, int d2): s1(d1), s2(d2){
   if (d1 < 1 || d2 < 1) {
      cerr << "illegal matrix size"
        << d1 << "by" << d2 << "\n";
      exit(1);
   }
   p = new int*[s1];
   for (int i = 0; i < s1; i++)
      p[i] = new int[s2];
}

matrix::~matrix(){
   for (int i = 0; i <= ub1(); ++i)
      delete p[i];
   delete []p;
}

The complete matrix code is also available in matrix.cpp inside the course download on the Resources page.

Submit your solution

Paste (1) your two add() implementations and (2) your discussion below, then click Submit. Your submission will take you directly to the results page, where your content will be displayed for review.