C++ - Friend Functions

Overview

Estimated time: 20–30 minutes

Grant controlled access to class internals for specific non-member functions or other classes.

Learning Objectives

  • Declare friend functions and understand trade-offs.

Example

class Box{ int w{0}; friend int width(const Box& b){ return b.w; } };

Common Pitfalls

  • Overusing friend breaks encapsulation; use sparingly for operators or tight coupling.