C++ Logo

std-proposals

Advanced search

Re: [std-proposals] opt-in inheritable friendship

From: Bo Persson <bo_at_[hidden]>
Date: Fri, 23 Oct 2026 10:05:50 +0200
On 2026-10-22 at 22:20, Theoden Cook via Std-Proposals wrote:
> Making a member public exposes it to all callers, while inheritable
> friendship grants access to only a specified class and its derived
> classes. The purpose is to preserve encapsulation while allowing an
> implementation hierarchy to access internals without requiring the
> granting class to enumerate every derived class.

The problem, as I see it, is that anynone can opt-in to being a friend,
without being "invited" by the original class. This is the opposite of
the current rules.

>
> On Thu, Oct 22, 2026 at 8:53 PM Bo Persson via Std-Proposals <std-
> proposals_at_[hidden] <mailto:std-proposals_at_[hidden]>> wrote:
>
> On 2026-10-22 at 21:20, Theoden Cook via Std-Proposals wrote:
> > Hello,
> >
> > I have an idea for a potential C++ language feature. I'd appreciate
> > feedback on whether it would be worth pursuing as a proposal.
> >
> > *The idea: opt-in inheritable friendship*
> > Currently in C++, friendship is neither inherited nor transitive.
> If a
> > class is declared as a friend of another class, its
> derived classes do
> > not inherit that friendship.
> >
> > I'd like to propose an opt-in mechanism that allows a class to
> > explicitly declare a friendship relationship as inheritable.
> >
> > For example, the syntax could look similar to this:
> > ```
> >
> > |class A { [[inheritable]] friend class B; private: void
> > internal_operation() {} }; class B {}; class C : public B
> { public: void
> > run(A& a) { a.internal_operation(); // Would be permitted } };|
> >
> > ```
> >
> > The [[inheritable]] syntax is illustrative. I'm open to
> alternatives :).
> >
> > The intended semantics would be that explicitly granting inheritable
> > friendship to B also grants the same access privileges to classes
> > derived from B, potentially across multiple levels of inheritance.
> > Ordinary friendship would retain its current behavior unless
> explicitly
> > marked as inheritable.
> >
> > The motivation is to make friendship compose more naturally with
> > inheritance, without requiring the granting class to explicitly
> friend
> > every derived class, or expose additional public/protected interface
> > solely to accommodate those classes.
> >
> How is this different from making the member public?
>
> class unrelated : B
> { };
>
> will get access, just like if internal_operation() were no longer
> private.
>

>

Received on 2026-10-23 08:05:56