|
|
|
|
|
|
|
When you pass Employee objects by reference (using pointers or references), all this is saved. This is why C++ programmers work hard never to pass anything larger than 4 bytes by value. |
|
|
|
|
|
|
|
|
Sometimes you will create classes together, as a set. These paired classes may need access to one another's private members, but you may not want to make that information public. |
|
|
|
|
|
|
|
|
New Term: If you want to expose your private member data or functions to another class, you must declare that class to be a friend. This extends the interface of your class to include the friend class. |
|
|
|
|
|
|
|
|
It is important to note that friendship cannot be transferred. Just because you are my friend and Joe is your friend doesn't mean Joe is my friend. Friendship is not inherited, either. Again, just because you are my friend and I'm willing to share my secrets with you doesn't mean I'm willing to share my secrets with your children. |
|
|
|
|
|
|
|
|
Finally, friendship is not commutative. Assigning Class One to be a friend of Class Two does not make Class Two a friend of Class One. Just because you are willing to tell me your secrets doesn't mean I am willing to tell you mine. |
|
|
|
|
|
|
|
|
Declarations of friend classes should be used with extreme caution. If two classes are inextricably entwined, and one must frequently access data in the other, there may be good reason to use this declaration. But use it sparingly; it is often just as easy to use the public accessor methods. Doing so allows you to change one class without having to recompile the other. |
|
|
|
|
|
|
|
|
You will often hear novice C++ programmers complain that friend declarations undermine the encapsulation so important to object-oriented programming. This is frankly errant nonsense. The friend declaration makes the declared friend part of the class interface and is no more an undermining of encapsulation than is public derivation. |
|
|
|
|
|
|