Friends
We've seen that overloading operators as member functions
and as non-member functions both have advantages and disadvantages.
The use of friend functions gives us the best of
both worlds.
A friend function is a non-member function which is granted permission
by the class to have direct access to the private members of the class.
Although we use Money's operator+ to illustrate friend functions, they
have other uses besides operator overloading.
To make a function a friend of a class, the non-member function prototype is
included in the class preceded with the keyword friend. A new version of
the Money class and new implementation of operator+
(display 8.3, text page 321) are shown below.
#include
#include
#include
using namespace std;
// Class for amounts of money in U.S. currency.
// Text display 8.3 (part 1), page 321 showing
// operator+ as a friend
// Modified for CMSC 202 coding standards
class Money
{
public:
Money( );
Money(double amount);
Money(int theDollars, int theCents);
Money(int theDollars);
double GetAmount( ) const;
int GetDollars( ) const;
int GetCents( ) const;
// Input() reads the dollar sign as well as the amount number.
void Input( );
void Output( ) const;
// make the non-member function our friend
friend const Money operator+ ( const Money& amount1, const Money& amount2);
private:
//A negative amount is represented as negative dollars and
//negative cents. Negative $4.50 is represented as -4 and -50
int m_dollars;
int m_cents;
int DollarsPart(double amount) const;
int CentsPart(double amount) const;
int Round(double number) const;
};
// Money's operator+ as a friend function
const Money operator+ (const Money& amount1, const Money& amount2)
{
int allCents1 = amount1.m_cents + amount1.m_dollars * 100;
int allCents2 = amount2.m_cents + amount2.m_dollars * 100;
int sumAllCents = allCents1 + allCents2;
// use abs() in case of negative money
int absAllCents = abs(sumAllCents);
int finalDollars = absAllCents / 100;
int finalCents = absAllCents % 100;
if (sumAllCents < 0)
{
finalDollars = -finalDollars;
finalCents = -finalCents;
}
return Money(finalDollars, finalCents);
}
Some folks argue that the use of friend functions violates the
principles of OOP. What do you think?
Last Modified: Monday, 28-Aug-2006 10:15:53 EDT