Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

friend — access for a nominated function or class

A friend declaration lets a nominated function or class access private and protected members without making it a member of the granting class.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

class Box {
    friend int read(const Box& box);
    friend class Inspector;
};

friend grants a nominated function or class access to private and protected members. The class containing the declaration grants permission; a friend function does not thereby become its member function.

friend int read(const Box& box); grants access to one specific function, not every overload of read. friend class Inspector; grants access to a class. Placing the declaration under public, protected, or private does not change its meaning.

Friendship is not reciprocal, inherited, or transitive. Grant it sparingly: it exposes implementation details.

In the example, read(box) reads value_. Calling box.read() would be invalid: read is not a member of Box. The source is an evolving standard draft; the example uses C++23-compatible syntax.

Examples

#include <iostream>

class Box {
    int value_ = 42;
    friend int read(const Box& box);
};

int read(const Box& box) {
    return box.value_;
}

int main() {
    Box box;
    std::cout << read(box) << '\n';
}

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources