Creating Friends

The first step toward creating a friend function is to place a prototype in the class declaration and prefix the declaration with the keyword friend:

friend Time operator*(double m, const Time & t);  // goes in class declaration

This prototype has two implications:

• Although the operator*() function is declared in the class declaration, it is not a member function. So it isn’t invoked by using the membership operator.

• Although the operator*() function is not a member function, it has the same access rights as a member function.

The second step is to write the function definition. Because it is not a member function, you don’t use the Time:: qualifier. Also you don’t use the friend keyword in the definition. The definition should look like this:

Time operator*(double m, const Time & t)  // friend not used in definition
{
    Time result;
    long totalminutes = t.hours * mult * 60 +t. minutes * mult;
    result.hours = totalminutes / 60;
    result.minutes = totalminutes % 60;
    return result;
}

With this declaration and definition, the statement

A = 2.75 * B;

translates to the following and invokes the nonmember friend function just defined:

A = operator*(2.75, B);

In short, a friend function to a class is a nonmember function that has the same access rights as a member function.

Actually, you can write this particular friend function as a non-friend by altering the definition so that it switches which value comes first in the multiplication:

Time operator*(double m, const Time & t)
{
    return t * m;     // use t.operator*(m)
}

The original version accessed t.minutes and t.hours explicitly, so it had to be a friend. This version only uses the Time object t as a whole, letting a member function handle the private values, so this version doesn’t have to be a friend. Nonetheless, there are reasons to make this version a friend, too. Most importantly, it ties the function in as part of the official class interface. Second, if you later find a need for the function to access private data directly, you only have to change the function definition and not the class prototype.


Tip

If you want to overload an operator for a class and you want to use the operator with a nonclass term as the first operand, you can use a friend function to reverse the operand order.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.50.156