codegurukool.com · Free coding tutorials & online compiler

Home › C++ Tutorial › C++ friend functions

C++ friend functions

Outside access to private members.

A friend function is not a member but may read private data. Use it sparingly.

Example code

#include <iostream>
using namespace std;
class Box {
  int w = 5;
  friend void show(Box b);
};
void show(Box b) { cout << b.w << endl; }
int main() {
  Box b; show(b);
  return 0;
}

Run this code in the online editor

← C++ access specifiers and encapsulationC++ inheritance →