`friend` — C++ Keyword

`friend` — C++ Keyword

The friend keyword in C++: grants a function or class access to private and protected members.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

friend

Grants a specific function or class access to the private and protected members of the class declaring the friendship.

Syntax

class Name {
    friend return-type function-name(params);
    friend class OtherClass;
};

Example

#include <print>

class Vector2 {
    double x_, y_;

public:
    Vector2(double x, double y) : x_(x), y_(y) {}

    // Friend function: accesses private x_, y_
    friend double dot(const Vector2& a, const Vector2& b) {
        return a.x_ * b.x_ + a.y_ * b.y_;
    }

    // Friend class
    friend class Matrix2;
};

class Matrix2 {
public:
    void inspect(const Vector2& v) const {
        std::println("x={} y={}", v.x_, v.y_);  // accesses private members
    }
};

int main() {
    Vector2 a{1, 0}, b{0, 1};
    std::println("{}", dot(a, b));   // 0

    Matrix2 m;
    m.inspect(a);   // x=1 y=0
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}