OOPortal 





Operator Overloading  «Prev  Next»
Lesson 5 Why friend functions are needed
Objective Write two add() functions to the matrix class
Write two add() functions to the matrix class
  1. one a friend function and
  2. the other a member function
and explain the advantages of defining one over the other.
The keyword friend is a function specifier and gives a non-member function access to the hidden members of the class, and provides a method of escaping the data hiding restrictions of C++. However, you must have a good reason for escaping these restrictions, as they are both important to reliable programming.
There are two reasons why you might use a friend function:
  1. Some functions need privileged access to more than one class. For example, we want to write a function that multiplies a matrix by a vector.
  2. All friend functions pass all their arguments through the argument list, and each argument value is subject to assignment-compatible conversions.
    Here is an example of this situation.
Conversions would apply to an object passed explicitly and would be especially useful in cases of binary operator overloading, as we will see a bit later in this module.
OO Programming in C++OO Programming in C++


Friend Function - Exercise
Click the Exercise link below to write two add() functions to the matrix class.
  1. one a friend function and
  2. the other a member function
and explain the advantages of defining one over the other.
Friend Function - Exercise