Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to understand C++ friend. When is the good use case to use friend? I suppose if we want to let another class have access to another classes attributes, why don't we just make it as public or inherit from that class instead?

Thank you for your help.

share|improve this question
I think this question definitely belongs here as it's more of a "why?" question than a "how?" question, and there have already been some good points made in the answers. – Larry Coleman Apr 16 '11 at 13:32
up vote 13 down vote accepted

Making a member of the class public means granting everyone access to it, thus breaking encapsulation completely.

Inheriting from a class is often not desirable, if the friend class is not meant to be a subclass. Subclassing just to get access to the internals of a class is a grave design mistake. And even a subclass can't see the private members of its base class.

A typical usage of friend is for operators that can't be members, such as stream operators, operator+ etc. In these cases, the actual class they are associated with is not (always) the first parameter of the function, so the function can't be implemented as a member method.

Another example is implementing an iterator for a collection. The iterator (and only the iterator) needs to see the internals of its parent collection, however it is not a subclass of the collection.

share|improve this answer
Sometimes, those free friend-functions are defined inline in the class. – Deduplicator Oct 7 '15 at 14:22

The example I've most often seen friend classes used for in C++ is in unit testing. Unit tests typically want to know all about your internals, but are not part of you, and it makes no sense to have them try to inherit from you.

If you aren't familiar with writing unit tests, I'd suggest that you start right away.

share|improve this answer
Production classes should know nothing about unit test classes. And the tests shouldn't need to see the internals of the tested class; a well designed class can be unit tested via its public API. If not, it is most likely not a well designed class (e.g. it tries to do too much, so part of its functionality should be better extracted into a separate class). – Péter Török Apr 17 '11 at 16:02
@peter-torok: That depends on what "well designed" means to you. A common case where I want privileged access is to inject mocks to track whether actions that were supposed to happen did. Exposing those parts of the object structure in the public API seems like a major violation of encapsulation. Therefore I often want unit test code to have privileged access. – btilly Apr 17 '11 at 18:06
@btilly: If you want to inject a mock you can use a parameter in the constructor, no need to access the internals of the class. – Giorgio Jan 2 '15 at 12:22
@PéterTörök GTest disagrees with you. There are some cases where a friend test would be helpful - for instance one might wish to compare the equivalence of two objects of the same class without exposing an equivalence operation in the API (perhaps for security concerns). – VF1 Jan 3 '15 at 2:02
@Giorgio Yes, you can make the information that you want to unit test be public. But now your public API just grew, and may lock you in to design decisions that would be unwise in the future. Put another way, it is appropriate to have unit tests for the edge cases of your current implementation. It is not always appropriate to expose that level of detail to consumers of your class. – btilly Jan 4 '15 at 5:11

This question should be on stackoverflow. Anyway You use a friend only when you want to share the private parts of your class with another class(or classes) but not with anyone else. If you make them public everyone can see your private parts( pun intended ;-P). There are two important restrictions which enforce privacy: 1) you have to specify who your friend is. No one else can be a freind. 2) you cannot inherit "friendly" behaviour in the friend class's subclasses

share|improve this answer
Socratic method question: And why is it bad to have everyone see your private parts? – Larry Coleman Apr 16 '11 at 13:34
@Larry: depends if it's done tastefully, or for shock value :D – Matt Ellen Apr 16 '11 at 15:02
@Matt: so is there a tasteful use of public variables? – Larry Coleman Apr 16 '11 at 15:13
@Larry: (non-euphemistically) when changing the state of the object, outside of the control of the object, won't cause the object to be in an invalid state. I think events in c# count in this respect. – Matt Ellen Apr 16 '11 at 15:17

A typical use is to grant access to functions that form part of the class' interface, but thanks to other rules can't really be part of the class proper. Inserters/extractors for iostreams are a classic example:

namespace whatever { 
    class something { 
        // ...    
        friend std::ostream &operator<<(std::ostream &os, something const &thing);
        friend std::istream &operator>>(std::istream &is, something &thing);

Making these operators members of the class will not work. An I/O operation looks something like:

whatever::something thing;

std::cout << thing;

For an operator implemented as a member function, this would be resolved as:


I.e., the function would have to be a member of std::cout, not of something. Since we don't want to modify std::ostream constantly, our only reasonable option is to overload the operator with a free function instead of a member function. That leaves us with two possibilities: either ignore encapsulation completely, and make everything in the class public, or else keep it private, but grant access to the few things that really need it.

Making another class a friend is rather less common. In this case, you're typically creating something on the order of a module or subsystem -- a set of classes that work together and have some degree of special access to each other that's not granted to the world at large.

share|improve this answer

There's a pretty good example of the need for friend classes in this request for friend-like classes in C#, a language that doesn't have them.

Quoted wholesale here:

Access modifiers in .NET were designed with the idea that you can trust your co-workers to know how the code works and hence not slip up and introduce a bug.

This idea is flawed though. Software development is so complicated that an experienced programmer knows not to even trust him/herself! For this reason, experienced programmers prefer to write code which, by design, cannot be broken through accidental misuse. .NET provides the tools to do this when only one class is involved, but the moment a programmer attempts to create a bullet-proof set of two or three interacting classes, this breaks down.

The .NET-intended approach to this is to mark the shared members as "internal", which allows the classes to interact with each others' internals. Unfortunately this also allows every other class in the assembly to mess with the internals, be it by accident or intentionally.

Mads Torgersen, C# Language PM, has even replied to this proposal, stating that the feels the concern is indeed a valid one, but being unsure about the specific implementation suggested there.

The C++ friend is just one of the ways to tackle the problem described.

share|improve this answer

When you want your classes to have monogamous relationships.

E.g. when you do not want unknown classes to access their privates, but their partners do need access.

share|improve this answer
Similar use-cases to those of internal in C# and package in Java. – Danny Varod Apr 17 '11 at 20:11

I've found friend classes in C++ to be useful where in Java I would have used package access. That is, I have a bunch of classes that are so intimately related that they are written and maintained as a unit, in the same source file(s). Anyone working on one of them is really working on all of them. The invariants that they maintain they maintain together. It makes sense for them to see each other's internals so they can maintain their shared invariant.

What doesn't make sense is protected access. If it's not safe to expose some part of my internals to the public, it's not safe to expose it to whatever jackanapes comes along later in a completely unrelated project and claims to be my subclass. Let subclasses use my public interface, just like everyone else. (Unless they're friends, but in that case I wrote them and implemented them in the same source, so they're hardly from some other project.)

share|improve this answer

Lets say there is an external function which requires you to perform operations on private or protected members of two different classes within your program. now, in order for that function to gain access and actualy use these class members you have to make it a friend of both classes. Keeping in mind that by making it a friend of both these classes does'nt make it a member of the classes it just gains the prevelage to refer to the private or protected members of these classes. I can say that you would need to use a friend function when you want to operate on objects of two different classes. Though the overuse of friend function and class can reduce the value of encapsulation.

share|improve this answer
this post is rather hard to read (wall of text). Would you mind editing it into a better shape? – gnat Oct 7 '15 at 13:42

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.