Friend Function Friends and Overloaded Operators Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software Design 2 A friend function is a function that is not a member of a class but has access to the class's private and protected members. Friend functions are not considered class members; they are normal external functions that are given special access privileges. Friends are not in the class's scope, and they are not called using the member-selection operators (. and >) unless they are members of another class. A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords. CSC 330 OO Software Design 3 // Example 1: friend_functions.cpp #include <iostream> using namespace std; class Point friend void ChangePrivate( Point & ); Point( ) : mi(0) void PrintPrivate( )cout << mi << endl; int mi; ; void ChangePrivate ( Point &i ) i.mi++; int main() Point spoint; spoint.printprivate( ); ChangePrivate(sPoint); spoint.printprivate( ); CSC 330 OO Software Design 4 // Example 2:Friends can access private members of a class. #include <iostream.h> class Count friend void setx( Count &, int ); // friend declaration Count() x = 0; // constructor void print() const cout << x << endl; // output int x; // data member ; // Can modify private data of Count because // setx is declared as a friend function of Count void setx( Count &c, int val ) c.x = val; // legal: setx is a friend of Count // Example 2 cont d: main program int main() Count counter; cout << "counter.x after instantiation: "; counter.print(); cout << "counter.x after call to setx friend function: "; setx( counter, 8 ); // set x with a friend counter.print(); return 0; CSC 330 OO Software Design 5 CSC 330 OO Software Design 6 1
Program Example: An Equality Function The DayOfYear class can be enhanced to include an equality function An equality function tests two objects of type DayOfYear to see if their values represent the same date Two dates are equal if they represent the same day and month Declaration of The equality Function We want the equality function to return a value of type bool that is true if the dates are the same The equality function requires a parameter for each of the two dates to compare The declaration is bool equal(dayofyear date1, DayOfYear date2); Notice that equal is not a member of the class DayOfYear CSC 330 OO Software Design 7 CSC 330 OO Software Design 8 Defining Function equal Using The Function equal The function equal, is not a member function It must use public accessor functions to obtain the day and month from a DayOfYear object equal can be defined in this way: bool equal(dayofyear date1, DayOfYear date2) return ( date1.get_month( ) == date2.get_month( ) && date1.get_day( ) == date2.get_day( ) ); The equal function can be used to compare dates in this manner if ( equal( today, bach_birthday) ) cout << "It's Bach's birthday!"; A complete program using function equal is found in CSC 330 OO Software Design 9 CSC 330 OO Software Design 10 Is equal Efficient? Function equal could be made more efficient Equal uses member function calls to obtain the private data values Direct access of the member variables would be more efficient (faster) A More Efficient equal As defined here, equal is more efficient, but not legal bool equal(dayofyear date1, DayOfYear date2) return (date1.month = = date2.month && date1.day = = date2.day ); The code is simpler and more efficient Direct access of private member variables is not legal! CSC 330 OO Software Design 11 CSC 330 OO Software Design 12 2
Declaring A Friend Friend Functions The function equal is declared a friend in the abbreviated class definition here class DayOfYear friend bool equal(dayofyear date1, DayOfYear date2); // The rest of the public members // the private members ; Friend functions are not members of a class, but can access private member variables of the class A friend function is declared using the keyword friend in the class definition A friend function is not a member function A friend function is an ordinary function A friend function has extraordinary access to data members of the class As a friend function, the more efficient version of equal is legal CSC 330 OO Software Design 13 CSC 330 OO Software Design 14 Using a Friend Function A friend function is declared as a friend in the class definition A friend function is defined as a nonmember function without using the "::" operator A friend function is called without using the '.' operator Friend Declaration Syntax The syntax for declaring friend function is class class_name friend Declaration_for_Friend_Function_1 friend Declaration_for_Friend_Function_2 Member_Function_Declarations Private_Member_Declarations ; CSC 330 OO Software Design 15 CSC 330 OO Software Design 16 Choosing Friends How do you know when a function should be a friend or a member function? In general, use a member function if the task performed by the function involves only one object In general, use a nonmember function if the task performed by the function involves more than one object Choosing to make the nonmember function a friend is a decision of efficiency and personal taste friend Functions A class's private members are accessible only to its methods and its friend functions. A class's protected members are accessible only to methods in its class hierarchy and its friend functions. To make a function f a friend of class C, we declare f within C's declaration using the keyword friend: class C // friend int f ( ); // friend function // CSC 330 OO Software Design 17 CSC 330 OO Software Design 18 3
friend Functions and friend Classes friend function of a class is defined outside that class s scope but has the right to access private and protected members of the class. A function or an entire class may be declared to be a friend of another class. To declare ClassTwo as a friend of class ClassOne place friend class ClassTwo in the declaration for ClassOne friendship is granted not taken Discussions Because f is not a method, the declaration serves only to give f access rights to C's private and protected members; thus, the declaration may be placed within the private, protected, or public part of the declaration of class C. Because a friend function is not a C++ method, yet has access to C's private and protected members, a friend function violates a strict interpretation of object-oriented principles. Note: It is recommend to use friend functions only in operator overloading. CSC 330 OO Software Design 19 CSC 330 OO Software Design 20 friend Functions cont d class Complex Complex( ); // default Complex( double ) ; // real given Complex( double, double ) ; // both given void write( ) const; // friend functions friend Complex operator+( const Complex&, const Complex& ) ; friend Complex operator-( const Complex&, const Complex& ) ; friend Complex operator*( const Complex&, const Complex& ) ; friend Complex operator/( const Complex&, const Complex& ) ; double real; double imag; ; Implementation File // Complex + as top-level friend Complex operator+( const Complex& t, const Complex& u ) return Complex( t.real + u.real, t.imag + u.imag ) ; // Complex - as top-level friend Complex operator-( const Complex& t, const Complex& u ) return Complex( t.real - u.real, t.imag - u.imag ) ; // Complex * as top-level friend Complex operator*( const Complex& t, const Complex& u ) return Complex( t.real * u.real - t.imag * u.imag, t.imag * u.real + t.real * u.imag ) ; // Complex / as top-level friend Complex operator/( const Complex& t, const Complex& u ) double abs_sq = u.real * u.real + u.imag * u.imag; return Complex( (t.real * u.real + t.imag * u.imag)/abs_sq, (t.imag * u.real - t-real * u.imag)/abs_sq); CSC 330 OO Software Design 21 CSC 330 OO Software Design 22 Rules for Overloading Operators When overloading an operator, at least one argument must be of the class type. You cannot create a new operator. All you can do is overload existing operators such as +, -, *, /, %, etc. You cannot change the number of arguments that an operator takes. For example, you cannot change % from a binary to a unary operator or change ++ from a unary to a binary operator. Rules for Overloading Operators cont d You cannot change the precedence of an operator. An overloaded operator has the same precedence as the ordinary version of the operator. For example, x * y + z always means (x * y) + z, even if x, y and z are objects. The following operators cannot be overloaded: the dot operator (.), the scope resolution operator (::), and the operators.* and?:. An overloaded operator can be a friend of the class or a member of the class. If you overload the assignment operator (=), it must be a member of the class, not a friend. CSC 330 OO Software Design 23 CSC 330 OO Software Design 24 4
Discussions Friendship (i.e., using the friend keyword) is a complex and dangerous topic for various reasons: Friendship, when applied to program design, is an escape mechanism allowing us to circumvent the principles of encapsulation and data hiding. The use of friends should therefore be minimized to situations where they can be used naturally. If friends are used, realize that friend functions or classes become implementation dependent on the classes declaring them as friends. Once the internal organization of the data of a class declaring friends changes, all its friends must be recompiled (and possibly modified) as well. Therefore, as a rule of thumb: don't use friend functions or friend classes. Discussions cont d Discussions cont d Should be used infrequently! Ordinary function (not member function) that has access to private members of class Specify friends in the class prototype (with keyword friend) Do not use dot operators when call (because ordinary function) Do not use scope resolution when define (because not member of class) At least one parameter should be of the class type Only reason for a friend: make function definition simpler and more efficient. Could accomplish same task using accessor/selector functions. CSC 330 OO Software Design 25 CSC 330 OO Software Design 26 5