TExcelTAD
Home › C++ › C++ Friend Functions

C++ Friend Functions

Private members are normally only accessible to the class's own member functions. Occasionally a function that is not a member needs that access too. C++ lets a class grant it explicitly by declaring the function a friend.

Declaring a friend function

The class lists the function inside its body with the keyword friend. The function itself is an ordinary free function — it is not called with obj. and has no this pointer:

cpp · try it yourself
#include <iostream>
using namespace std;

class Box {
public:
    Box(double w, double h, double d) : width(w), height(h), depth(d) {}

    friend double volume(const Box& b);   // grant access

private:
    double width, height, depth;
};

double volume(const Box& b) {             // a normal function, not Box::volume
    return b.width * b.height * b.depth;  // may read private members
}

int main() {
    Box crate(2, 3, 4);
    cout << "Volume: " << volume(crate) << "\n";
}
Volume: 24

Key points:

  • Friendship is granted by the class, never taken: a function cannot declare itself a friend of some class.
  • It does not matter whether the friend declaration is in the public or private section.
  • Friendship is not inherited and not transitive: a friend of A is not automatically a friend of classes derived from A.

The classic use: operator<<

The most common friend in real code is the stream output operator. It must be a free function because its left operand is the stream (cout << obj), not your object, yet it needs to print the private data:

cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

class Fraction {
public:
    Fraction(int n, int d) : num(n), den(d) {}

    friend ostream& operator<<(ostream& os, const Fraction& f) {
        return os << f.num << "/" << f.den;
    }

private:
    int num, den;
};

int main() {
    Fraction half(1, 2), third(1, 3);
    cout << half << " and " << third << "\n";
}
1/2 and 1/3

Defining the friend directly inside the class, as above, is a common and tidy shortcut. Operator overloading is covered in its own lesson.

A function friend of two classes

A friend function is handy when an operation naturally involves the private data of two different classes:

cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

class Wallet;   // forward declaration

class Person {
public:
    explicit Person(string n) : name(n) {}
    friend void pay(Person& p, Wallet& w, int amount);
private:
    string name;
    int purchases = 0;
};

class Wallet {
public:
    explicit Wallet(int c) : cash(c) {}
    friend void pay(Person& p, Wallet& w, int amount);
private:
    int cash;
};

void pay(Person& p, Wallet& w, int amount) {
    if (w.cash >= amount) {
        w.cash -= amount;
        p.purchases++;
        cout << p.name << " paid " << amount << ", cash left " << w.cash << "\n";
    } else {
        cout << p.name << " cannot afford " << amount << "\n";
    }
}

int main() {
    Person li("Li");
    Wallet w(50);
    pay(li, w, 20);
    pay(li, w, 40);
}
Li paid 20, cash left 30
Li cannot afford 40

Friend classes

A whole class can be made a friend. All of its member functions then get access to the private members:

cpp · try it yourself
#include <iostream>
using namespace std;

class Engine {
    friend class Mechanic;     // Mechanic may access everything in Engine
private:
    int wear = 73;
    void reset() { wear = 0; }
};

class Mechanic {
public:
    void service(Engine& e) {
        cout << "wear before: " << e.wear << "\n";
        e.reset();
        cout << "wear after: " << e.wear << "\n";
    }
};

int main() {
    Engine engine;
    Mechanic m;
    m.service(engine);
}
wear before: 73
wear after: 0

Use friends sparingly

Good reasons Warning signs
Stream operators << and >> Making half your program a friend
Symmetric operators like == or + Using friends to avoid designing a proper public interface
Tightly coupled helper classes (iterators, builders) Friend classes in unrelated parts of the codebase

Note: A friend is part of the class's interface in all but name — it is declared inside the class, after all. Used deliberately, friends do not break encapsulation; they extend it to functions that genuinely belong with the class.

Test yourself

Who decides that a function is a friend of a class?

  1. The function itself
  2. The class, by declaring it with friend
  3. The compiler automatically
  4. Any derived class

Does a friend function have a this pointer?

  1. Yes
  2. No, it is not a member function
  3. Only if declared public
  4. Only inside the class body

If B derives from A, and f is a friend of A, is f a friend of B?

  1. Yes, friendship is inherited
  2. No, friendship is not inherited
  3. Only for public members
  4. Only if B is a struct