← Previous · All Episodes · Next →
Unveiling Self-Friendship in C++: A Deep Dive into Unique Class Relationships Episode

Unveiling Self-Friendship in C++: A Deep Dive into Unique Class Relationships

· 01:20

|

Hello and welcome to C++ Spotlight. Today we’re digging into a surprising technique: declaring a class as its own friend. Directly doing so even triggers a compiler warning: “class ‘C’ is implicitly friends with itself.” But there are two practical scenarios where it makes sense.

First, imagine a templated Wrapper class. Inside Wrapper you write
template friend class Wrapper;
This lets one specialization, like Wrapper, access private members of another, say Wrapper. In the author’s example, Wrapper calls accessSecret and prints a private secret from Wrapper.

Second, nested classes. If Inner declares
friend class Outer;
then the Outer class can peek into Inner’s private state. In the demo, Outer calls revealSecret and prints “Inner’s secret is: 42.”

While uncommon, these patterns let related types share internals without exposing them globally. Have you ever used self-friendship tricks in your own C++ code? Thanks for listening!
Link to Article


Subscribe

Listen to jawbreaker.io using one of many popular podcasting apps or directories.

Apple Podcasts Spotify Overcast Pocket Casts Amazon Music
← Previous · All Episodes · Next →