Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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
2  
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
add comment

6 Answers

up vote 12 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
add comment

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
1  
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
1  
@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
add comment

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
2  
@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
add comment

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:

std::cout.operator<<(thing);

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
add comment

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
add comment

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
add comment

Your Answer

 
discard

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.