CJCoding With Joseph
15free / daySign inCreate account

Mastering C++

Friend Functions

Classes In C++

A – What Is a Friend Function?

A friend function is a function that is not part of a class, but it is given special access to the class’s private and protected members. Normally, only class methods can access private variables. But a friend function breaks that rule because the class trusts it.

To declare a function as a friend, you use the keyword friend inside the class declaration.

This is useful in cases like:

  • Overloading operators (like << for printing)

  • Helper functions that need access to private values

  • Comparing or combining two different classes

Even though the function is defined outside the class, it can "see" the class's private variables.


B – Declaring and Using a Friend Function

Let’s say we have a class called Box, and we want a function called printBox to print the width, which is private.

Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 21 more lessons in Mastering C++.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.