Chapter 27 of 48

Friend Functions & Classes

In Classes & Objects we learned that private members can be used only by the class's own member functions. That rule is the heart of encapsulation: outside code cannot reach in and break an object's data.

Sometimes, though, a function that is not a member genuinely needs to see private data. Printing an object with std::cout << obj, comparing objects of two different classes, or a tightly coupled helper class are common examples. For these cases C++ lets a class name specific outsiders it trusts. These trusted outsiders are called friends.

In this chapter you will learn friend functions, friend member functions, friend classes, the rules of friendship, and the modern "hidden friend" idiom.


What Is a Friend Function?

A friend function is a function that is not a member of a class but has been granted access to the class's private and protected members. The class grants this access by declaring the function inside its body with the keyword friend.

Think of a house (the class) and a trusted family friend. The friend does not live in the house (is not a member), but the owner has given them a key (access). Importantly, the owner decides who gets a key; nobody can declare themselves a friend from outside.

Syntax

class ClassName {
    // ...
    friend ReturnType functionName(parameters);   // declaration inside the class
};

ReturnType functionName(parameters) {             // ordinary definition outside
    // can access private members of ClassName objects
}

A First Example

#include <iostream>

class Box {
    double width;                    // private

public:
    explicit Box(double w) : width(w) {}

    friend void printWidth(const Box& b);   // grant access
};

// Defined like an ordinary function: no 'friend', no 'Box::'
void printWidth(const Box& b) {
    std::cout << "Width: " << b.width << '\n';   // OK: friend can read private data
}

int main() {
    Box box(12.5);
    printWidth(box);    // called like a normal function, not box.printWidth()
}

Output:

Width: 12.5

Points to notice:

  • The keyword friend appears only in the declaration inside the class.
  • The definition is written like a normal function: no friend, no Box:: prefix, because it is not a member of Box.
  • It is called as printWidth(box), not box.printWidth().
  • A friend function has no this pointer, so the object must be passed as a parameter and members are accessed through it (b.width).
  • It does not matter whether the friend declaration is written in the public, private or protected section. Access specifiers apply to members, and a friend is not a member.

A Friend of Two Classes

The classic textbook use of friend functions is an operation that needs the private data of two different classes. A member function can belong to only one class, but one free function can be a friend of both.

#include <iostream>

class Rupees;   // forward declaration: Dollars needs to mention Rupees

class Dollars {
    double amount;
public:
    explicit Dollars(double a) : amount(a) {}
    friend bool isMore(const Dollars& d, const Rupees& r);
};

class Rupees {
    double amount;
public:
    explicit Rupees(double a) : amount(a) {}
    friend bool isMore(const Dollars& d, const Rupees& r);
};

// One function, friend of BOTH classes, can read both private members
bool isMore(const Dollars& d, const Rupees& r) {
    const double rate = 88.0;   // assumed rate for the example
    return d.amount * rate > r.amount;
}

int main() {
    Dollars d(10);
    Rupees r(800);
    std::cout << std::boolalpha << isMore(d, r) << '\n';
}

Output:

true

Working: 10 dollars × 88 = 880 rupees, which is more than 800, so the answer is true.

The line class Rupees; is a forward declaration. When the compiler reads the friend declaration inside Dollars, it needs to know that Rupees is a class name. Only the name is required at that point, because a function declaration may mention an incomplete class in its parameter list; the full definition of Rupees is needed later, where the function body actually reads r.amount.


A Member Function of Another Class as a Friend

You can be selective and befriend just one member function of another class, instead of the whole class:

#include <iostream>
#include <string>
#include <utility>

class Engine;   // forward declaration

class Mechanic {
public:
    void inspect(const Engine& e) const;   // only declared here
    void wash(const Engine& e) const;
};

class Engine {
    int temperature = 92;
    std::string serial;
public:
    explicit Engine(std::string s) : serial(std::move(s)) {}

    // Only this ONE member function of Mechanic is a friend
    friend void Mechanic::inspect(const Engine& e) const;
};

// Defined after Engine is complete, so its members are known
void Mechanic::inspect(const Engine& e) const {
    std::cout << "Engine " << e.serial << " at " << e.temperature << " C\n";
}

void Mechanic::wash(const Engine&) const {
    // e.temperature here would be an error: wash() is not a friend
    std::cout << "Washing the engine\n";
}

int main() {
    Engine e("EN-42");
    Mechanic m;
    m.inspect(e);
    m.wash(e);
}

Output:

Engine EN-42 at 92 C
Washing the engine

The ordering here matters and is a common exam question:

  1. Engine is forward-declared so that Mechanic can mention it in parameter lists.
  2. Mechanic must be fully defined before Engine, because the declaration friend void Mechanic::inspect(...) names a member of Mechanic, and the compiler must already know that member exists.
  3. The body of Mechanic::inspect is written after Engine is complete, because it reads Engine's members.

Mechanic::wash is not a friend, so it cannot touch e.temperature.


Friend Classes

If a class needs many functions of another class to access its internals, you can make the entire class a friend:

When class A declares friend class B;, every member function of B can access the private and protected members of A.

#include <iostream>

class BankAccount {
    double balance = 0;
    int pin = 1234;

    friend class Auditor;   // every member function of Auditor is a friend
public:
    void deposit(double amt) { balance += amt; }
};

class Auditor {
public:
    void report(const BankAccount& acc) const {
        std::cout << "Balance: " << acc.balance << '\n';
    }
    bool pinLooksWeak(const BankAccount& acc) const {
        return acc.pin == 1234;
    }
};

int main() {
    BankAccount acc;
    acc.deposit(5000);

    Auditor a;
    a.report(acc);
    std::cout << std::boolalpha << a.pinLooksWeak(acc) << '\n';
}

Output:

Balance: 5000
true

Friend classes are typical for pairs of classes designed together, for example a container and its iterator, or a linked list and its node class.


The Rules of Friendship

Friendship in C++ is deliberately limited. Remember these three properties:

PropertyMeaning
Not mutual (not symmetric)If A declares B a friend, B can access A's privates, but A cannot access B's privates unless B also declares A a friend.
Not transitiveIf B is A's friend and C is B's friend, C is not A's friend. "A friend of my friend is not my friend."
Not inheritedIf B is A's friend, a class derived from B is not automatically A's friend. Likewise, A's friends get no special access to classes derived from A beyond A's own members.

Let's prove the first and third rules with the compiler. (Derived classes are covered properly in the Inheritance chapter; here we only need the fact that C is built from B.)

class B;

class A {
    int secretA = 1;
    friend class B;          // A says: "B is my friend"
public:
    int peekB(const B& b);   // defined below, after B is complete
};

class B {
    int secretB = 2;
public:
    int peekA(const A& a) { return a.secretA; }   // OK: B is A's friend
};

int A::peekB(const B& b) {
    return b.secretB;        // error: friendship is NOT mutual
}

class C : public B {
public:
    int peekA2(const A& a) { return a.secretA; }  // error: friendship is NOT inherited
};

Compiler errors (g++ 15, abridged):

f5.cpp:17:14: error: ‘int B::secretB’ is private within this context
f5.cpp:22:39: error: ‘int A::secretA’ is private within this context

B::peekA compiles fine. A::peekB fails because B never called A its friend, and C::peekA2 fails because C did not inherit B's friendship.


Defining a Friend Inside the Class: Hidden Friends

A friend function can also be defined directly inside the class body. It is still a non-member function (and implicitly inline):

#include <iostream>

class Point {
    int x, y;
public:
    Point(int x, int y) : x(x), y(y) {}

    // "Hidden friend": declared AND defined inside the class
    friend double distanceSq(const Point& a, const Point& b) {
        int dx = a.x - b.x, dy = a.y - b.y;
        return dx * dx + dy * dy;
    }
};

int main() {
    Point p(1, 2), q(4, 6);
    std::cout << distanceSq(p, q) << '\n';   // found by argument-dependent lookup
}

Output:

25

Here 3² + 4² = 9 + 16 = 25.

A friend that is declared only inside the class (with no matching declaration outside) is called a hidden friend. Ordinary name lookup cannot see it; it is found only through argument-dependent lookup (ADL), that is, because one of the arguments is a Point. This is a good thing: the function cannot be called accidentally with unrelated types, and the compiler has fewer overloads to consider. Modern C++ style guides recommend hidden friends for operators such as == and <<.


The Most Common Real-World Friend: operator<<

To print an object with std::cout << obj, the left operand is std::cout, an std::ostream. We cannot add a member function to the standard library's ostream class, so the operator must be a non-member. And since it needs private data, it is usually a friend:

#include <iostream>

class Temperature {
    double celsius;
public:
    explicit Temperature(double c) : celsius(c) {}

    // Lets us write: std::cout << t;
    friend std::ostream& operator<<(std::ostream& os, const Temperature& t) {
        return os << t.celsius << " C";
    }
};

int main() {
    Temperature t(36.6);
    std::cout << "Body temperature: " << t << '\n';
}

Output:

Body temperature: 36.6 C

Returning the stream by reference is what allows chaining like std::cout << "a" << t << '\n'. The full story of overloading operators comes in the next chapter, Operator Overloading.


Member vs Static Member vs Friend

All three can access private data, but they differ in how they are called:

#include <iostream>

class Counter {
    int value = 0;
public:
    // member: called on an object, has 'this'
    void incrementMember() { ++value; }

    // static member: no object, no 'this'
    static Counter makeAt(int v) { Counter c; c.value = v; return c; }

    // friend: not a member, no 'this', takes the object explicitly
    friend void incrementFriend(Counter& c) { ++c.value; }

    int get() const { return value; }
};

int main() {
    Counter c = Counter::makeAt(10);
    c.incrementMember();
    incrementFriend(c);
    std::cout << c.get() << '\n';
}

Output:

12
FeatureMember functionStatic member functionFriend function
Belongs to class scopeYesYesNo
Has thisYesNoNo
Call syntaxobj.f()Class::f()f(obj)
Access to private membersYesYesYes
Can be virtualYesNoNo
Affected by public/private placementYesYesNo
Inherited by derived classesYesYesNo (friendship is not inherited)
Left operand can be a non-class type (e.g. ostream, int)NoNot applicableYes

Do Friends Break Encapsulation?

This is a common interview discussion. The short answer is: used properly, no.

  • Encapsulation means the class controls who can touch its data. With friend, the class itself lists every outsider it trusts, in its own definition. Nobody can grant themselves access.
  • A friend function is really part of the class's interface; it is just written with non-member syntax (for example operator<<, or a symmetric operator+).
  • The alternative, adding public getters and setters for everything, often exposes data to every function in the program, which is worse.

That said, a long list of friends is a design smell. If many unrelated classes need private access, the class's public interface is probably missing something.


Common Mistakes

  • Writing friend or ClassName:: in the definition of a friend function defined outside the class. Both are wrong; it is a plain function.
  • Calling it with dot syntax, as in box.printWidth(). A friend is not a member.
  • Forgetting the forward declaration when one function is a friend of two classes.
  • Wrong order with a friend member function: the class whose member is befriended must be completely defined first.
  • Assuming friendship is mutual, transitive or inherited. It is none of these.
  • Using this inside a friend function. There is none.

Interview / Exam Questions

1. Is a friend function a member of the class?

No. It is a non-member function that has been granted access to the class's private and protected members. It has no this pointer and is not called through an object.

2. If class A is a friend of class B, is B a friend of A?

No. Friendship is not mutual. B would have to declare friend class A; explicitly.

3. Can a friend function be declared in the private section? Does that make it private?

Yes, it can be declared anywhere in the class body, and the placement has no effect. Access specifiers control access to members; a friend is not a member.

4. Why is operator<< for output usually a friend rather than a member?

For std::cout << obj, the left operand is an std::ostream. A member operator would need to be a member of ostream, which we cannot modify. So it must be a non-member, and making it a friend gives it access to the private data it prints.

5. Can a friend function be virtual?

No. Virtual dispatch applies only to non-static member functions. A common workaround is to have the friend call a virtual member function, for example operator<< calling a virtual print(std::ostream&).

6. Class B is a friend of A. Class D derives from B. Can D's member functions access A's private members?

No. Friendship is not inherited. Only member functions declared in B itself get access; D's own functions do not (though D can call B's functions, which do have access).


Summary

  • A friend function is a non-member function given access to a class's private and protected members by a friend declaration inside that class.
  • You can befriend a free function, a single member function of another class, or an entire class.
  • Friendship is not mutual, not transitive and not inherited.
  • Friend functions have no this, are called like ordinary functions, and ignore access-specifier placement.
  • A friend defined inside the class is a hidden friend, found only via argument-dependent lookup; it is the preferred style for operators.
  • The most common practical use is operator<< and other symmetric operators, which we explore next in Operator Overloading.