Lesson 140 +10 XP

Friend Functions

Friend Functions

Everything private in a class stays hidden from the outside - normally. A friend function steps around that: it is declared with friend inside the class, which grants it permission to access the class's private members even though it is not a member of the class.

class Car {
private:
  int year;
public:
  friend void showYear(const Car& c);   // friendship granted
};

The function then uses the private members freely:

void showYear(const Car& c) {
  cout << c.year;     // private, but the friend can see it
}

The function is declared inside the class but defined outside with no Car:: prefix - it is still a plain non-member function.

When to use friends

Friend functions shine for operators and helpers that feel naturally attached to a class, like printing an object. Use them sparingly: every friend is a deliberate hole in the class's encapsulation.

TL;DR

  • friend is declared inside the class but the function is not a member.
  • It grants one function access to private (and protected) members.
  • It is defined outside with no class prefix.
  • They are powerful but should be rare.