Labs ICT
🎓 SIWES/IT Login

Friend Functions

1 min read | C++ Tutorial
🎓

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

Friend Functions

A friend function is a non-member function that has access to a class's private and protected members. Declare it inside the class with the friend keyword.

When to Use

Friend functions are useful for operator overloading and when two classes need tight cooperation. They break encapsulation, so use them sparingly.

#include <iostream>
using namespace std;

class Box {
private:
  double length;

public:
  Box(double l) {
    length = l;
  }

  friend void printLength(Box b);
};

void printLength(Box b) {
  cout << "Length: " << b.length << "\n";
}

int main() {
  Box box(10.5);
  printLength(box);
  return 0;
}