Skip to content
  • Friend Functions & Classes · C++

Friend Functions & Classes

LearnViaNotes @learnvianotes· 2 min read

A friend declaration grants a specific function or class access to a class's private members — a controlled exception to encapsulation.

Friend function

C++
#include <iostream>

class Fraction {
    int num_, den_;
public:
    Fraction(int n, int d) : num_(n), den_(d) {}
    friend std::ostream& operator<<(std::ostream& os, const Fraction& f) {   // hidden friend
        return os << f.num_ << '/' << f.den_;
    }
    friend Fraction operator*(const Fraction& a, const Fraction& b) {
        return {a.num_ * b.num_, a.den_ * b.den_};
    }
    friend bool sameValue(const Fraction& a, const Fraction& b);
};

bool sameValue(const Fraction& a, const Fraction& b) {    // defined outside, still a friend
    return a.num_ * b.den_ == b.num_ * a.den_;
}

int main() {
    Fraction half(1, 2), third(1, 3);
    std::cout << half * third << ' ' << sameValue(half, Fraction(2, 4)) << '\n';
}
Output
1/6 1

Friend class

C++
#include <iostream>

class Engine {
    int rpm_ = 0;
    friend class Mechanic;          // Mechanic may touch Engine's privates
};

class Mechanic {
public:
    static void tune(Engine& e, int rpm) { e.rpm_ = rpm; }
    static int read(const Engine& e) { return e.rpm_; }
};

int main() {
    Engine e;
    Mechanic::tune(e, 3000);
    std::cout << Mechanic::read(e) << '\n';
}
Output
3000
  • Friendship is granted, not taken — the class decides who its friends are.

  • It's not symmetric (A friend of B doesn't make B a friend of A), not transitive, and not inherited.

  • A hidden friend (defined inside the class) is found only by argument-dependent lookup — the preferred way to write operators.

Does friend break encapsulation?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report