Study Guide · 07
Friend Functions
Non-member functions allowed to reach a class's private members
1
Notes
2
Videos by Dr. Ibrahim Albluwi
3
Code examples
Key Concepts
This page is a short summary. The full notes are in Friend Function.pdf on Google Drive.
Summary
01 · What is a friend function?
02 · Example
03 · Friend of several classes
- One function can be a friend of more than one class, reading each one's private data while belonging to none.
- Both classes declare
friend void showSum(const ClassA& a, const ClassB& b);and it is called asshowSum(objA, objB); - Forward-declare the second class before the first one uses it:
class ClassB;
Extra Notes · beyond the PDF
Rules of friendship
- Friendship is granted, not taken — only the class itself can declare its friends.
- It isn't mutual: if A is a friend of B, B is not automatically a friend of A.
- It isn't inherited and isn't transitive — a friend of a friend is not a friend.
- The friend declaration can go in the
publicorprivatepart; it means the same thing.