friend Functions


While classes are created to encapsulate the private members, there are times when it is desirable to get at these members with non-member functions. This is possible using friend functions. A friend function is defined outside of the class definition. It is usually declared in the public access section of the class but may be declared in any access section. The declaration of the function is preceded by the keyword friend.

There are several ways in which a friend function could be used. A friend function can be defined:

  • to access two or more classes to permit the movement of data between the different objects of different classes but this function would not be a member of either class.

  • to access private members of a single class but it is not a member function of any class.

  • to be a member function of one class but to have access to the private members of a second class.

An example is bnkacnts.cpp. In this example three classes are defined: Checking, Savings and Money. In each class the function approved() is declared in the following manner:

image from book

 bool friend approved(Checking c, Savings s, Money m); 

image from book

and outside of the definitions of each of the classes, the function is defined as follows:

image from book

 bool approved(Checking c, Savings s, Money m) {   bool is_approved = false;   if((c.amount+s.amount+m.amount)>10000)      is_approved = true;   return is_approved; } 

image from book

Notice above that the keyword friend does not appear in the definition of the function approved().

Notice that the classes: Davings and Money were declared above the definition of the class Checking. This was done by the following statements:

image from book

 class Savings; class Money; 

image from book

This was necessary because the declaration of approved() contains signature references to these classes before they are defined.

As stated above, friend functions may be declared in any access section. See bnkacntx2.cpp. This is in general the same example as before except that this time the friend function is declared in the private access section of the classes yet the program still compiles.

The existence of friend functions is in opposition to the OOP philosophy. Since friends are able to get at private members and yet are not member functions, they seem to oppose the concept of encapsulation. The programmer should guard against using these functions except where they are absolutely necessary. The one saving property is that a function can not be a friend arbitrarily because the class to which they are a friend must permit this friend status.




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net