OOPortal OOPortal

Operator Overloading  «Prev 

C++ Friend Function - Exercise

Using a friend function or a member function

Objective: Write two add() functions to the matrix class, one a friend function and the other a member function and explain the advantages of defining one over the other.


Write two add() functions for the following matrix class. These functions, when given two matrices, return a matrix where each element is the sum of the corresponding elements of the argument matrices.
The first add() function will be a nonmember friend function and will have the following declaration:

friend matrix  add(const matrix& m1, const matrix& m2);

The second add() function will be a member function of the matrix class with the following prototype:

matrix  matrix::add(const matrix& m);

In addition to submitting the code for these functions, include a discussion of the advantages of defining one function over the other.

The matrix class

Here is the code for the matrix class:

class matrix {
   matrix(int d);
   matrix(int d1, int d2);
   int ub1() const { return (s1 - 1); }
   int ub2() const { return (s2 - 1); }
   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";
   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";
   p = new int*[s1];
   for (int i = 0; i < s1; i++)
      p[i] = new int[s2];

   for (int i = 0; i <= ub1(); ++i)
      delete p[i];
   delete []p;
The code for the matrix class is available in a file named matrix.cpp, which can be found in the compressed course download file available on the Resources page.
Paste your code and your discussion below and click the Submit button when you are ready to submit this exercise.