«Prev  Next»

C++ Friend Function vs Member Function - Exercise Results

Your submission

Below is the text you submitted from the exercise page. This page displays your input first, then shows a reference solution and an explanation structured around the objective.

No submission was received. Return to the exercise page and click Submit.

Objective recap

The objective was to implement two versions of add() for a matrix type:

Both functions should return a new matrix where each element is the sum of corresponding elements in the two inputs, and they should validate that the dimensions match.

Reference solution

One acceptable implementation is shown below. It relies on friend access for the nonmember function (so it can read p, s1, and s2 directly), and it uses member access for the member version.

matrix add(const matrix& m1, const matrix& m2) {
  // Check dimensions match
  assert((m1.s1 == m2.s1) && (m1.s2 == m2.s2));

  matrix ans(m1.s1);
  int i, j;

  for (i = 0; i <= m1.ub1(); ++i) {
    for (j = 0; j <= m1.ub2(); ++j) {
      ans.p[i][j] = m1.p[i][j] + m2.p[i][j];
    }
  }
  return ans;
}
matrix matrix::add(const matrix& m) {
  // Check dimensions match
  assert((s1 == m.s1) && (s2 == m.s2));

  matrix ans(s1);
  int i, j;

  for (i = 0; i <= ub1(); ++i) {
    for (j = 0; j <= ub2(); ++j) {
      ans.p[i][j] = p[i][j] + m.p[i][j];
    }
  }
  return ans;
}

Explanation (structured around the objective)

1) Why the friend nonmember version exists

The nonmember function is declared as a friend so it can access the private representation of both matrices (p, s1, s2) without requiring public getters. This can be useful when an operation naturally treats both operands symmetrically:

matrix c = add(a, b);

2) Why the member version exists

The member function is invoked on a left-hand operand and takes the right-hand operand as a parameter. That makes the call-site read naturally as “add this matrix to that matrix”:

matrix c = a.add(b);

3) Advantages and tradeoffs

Continue

If you want to revise your answer, return to the exercise page and resubmit.

« Return to Exercise