C++ Logo

std-proposals

Advanced search

[std-proposals] The limits of friendship

From: Magnus Fromreide <magfr_at_[hidden]>
Date: Wed, 7 May 2025 02:04:55 +0200
Hello!

I tried to declare two classes:

class A {
private:
        void f();
        void g();
};

class B {
private:
        friend void A::f();
        void x();
};

and then got surprised when my compiler told me that I need to be able to
call A::f in order to grant it friendship.

I am perfectly happy with not beeing able to call or take the address of
A::f but I think it should be possible to grant friendship to a private
member.

In summary, what I expected to happen is that

* The declarations of A and B compile as written.
* A::f() can call B::x().
* A::g() can't call B::x().
* B::x() can't call neither A::f() nor A::g().

The rule that the target of friendship must be declared will still apply
so

class C {
        friend void A::x();
};

is still a compilation error because A::x doesn't exist.

/MF

Received on 2025-05-07 00:05:00