Friend Functions ..................................................................................................
You just learned that declaring another class a friend gives it total access. At times, you
might want to grant this level of access not to an entire class, but only to one or two
functions of that class. You can do this by declaring the member functions of the other
class to be friends, rather than declaring the entire class to be a friend. In fact, you can
declare any function, regardless of whether it is a member function of another class, to
be a friend function.
Friend Functions and Operator Overloading ......................................................
Listing 16.1 provided a Stringclass that overrode the operator+. It also provided a con-
structor that took a constant character pointer, so that string objects could be created
from C-style strings. This enabled you to create a string and add to it with a C-style
string.
580 Day 16
You will often hear novice C++ programmers complain that friend declara-
tions “undermine” the encapsulation so important to object-oriented pro-
gramming. This is not necessarily true. The friend declaration makes the
declared friend part of the class interface and does not have to undermine
encapsulation. Use of a friend implies a commitment to parallel mainte-
nance of both classes, which could reduce modularity.
NOTE
Friend Class
Declare one class to be a friend of another by putting the word friendinto the class granting
the access rights. That is, I can declare you to be my friend, but you can’t declare yourself to be
my friend.
Example
class PartNode{
public:
friend class PartsList; // declares PartsList to be a friend of PartNode
};
C-style strings are null-terminated character arrays, such as char myString[]
= “Hello World”.
NOTE