views:

4712

answers:

10

I was just brushing up on my cpp (I'm a java developer) and I came across the Friend class keyword which I forgot about for a while. Is this one of those features that's just part of the kitchen sink, or is there a good reason for doing this rather than just a vanilla getter? I understand the difference in that it limits who can access the data, but I can't think of a scenario when this would be necessary.

Note: I've seen a similar question, but specifically I'm asking, is this just an advanced feature that adds no real value except to confuse people looking at you're code until they realize what you're doing?

+12  A: 

In my experience, the cases when friend (or mutable, which is a little similar) to actually enhance encapsulation of data are rare compared with how often it's used to break encapsulation.

It's rarely useful to me but when I do use it it's for cases in which I've had to split a class that was formerly a single class into two separate classes that need to access some common data/functionality.

Edit to respond to Outlaw Programmer's comment: We absolutely agree on this. One other option apart from friend'ing classes after splitting them is to make public accessors, which sometimes break encapsulation! I think that some people think that friendly classes somehow breaks encapsulation because they've seen it used improperly a lot, and many people probably never see code where it's been used correctly, because it's a rare thing. I like your way of stating it though - friendliness is a good middle ground between not allowing you to split up your class and making EVERYTHING accessible to the public.

Edit to respond to David Thornley: I agree that the flexibility that C++ allows you to do things like this is a result of the design decisions that went into C++. I think that's what it makes it even more important to understand what things are generally good and bad style in flexible languages. Java's perspective is that you should never have friend classes so that these aren't provided, but as C++ programmers it's our responsibility as a community to define appropriate use of these very flexible but sometimes misused language constructs.

Edit to respond to Tom: Mutable doesn't necessarily break encapsulation, but many of the uses of the mutable keyword that I've seen in real-life situations break encapsulation, because it's much more common to see people breaking encapsulation with mutable than to actually find and understand a proper use of mutable in the first place.

James Thompson
+1 Sometimes you might have to extract a new class from an existing one for, say, readability issues but you still want to keep the tight coupling. You want to give the new class special access but don't want to make these methods public.
Outlaw Programmer
David Thornley
why does `mutable` break encapsulation?
Tom
i tend to think of "friend" as a out-of-class member, which can also access private data. somewhat analogous to the "package private" protection in java. You have different pieces doing separate work, but they can benefit from having access to other's implementation - maybe for speed increase.
Johannes Schaub - litb
+1  A: 

I look at the friend construct as one of those features of the language that should be used in rare occasions, but that doesn't make it useless. There are several patterns that call for making friend classes, many of them already on this site in that "Related" bar on the right. ====>

Scottie T
+3  A: 

Helps with Memento design pattern

Nemanja Trifunovic
+16  A: 

I agree with the comments that say the friend keyword can improve encapsulation if used wisely. I'd just add that the most common (legitimate!) use for friend classes may be testing. You may want a tester class to have a greater degree of access than other client classes would have. A tester class could have a good reason to look at internal details that are deliberately hidden from other classes.

John D. Cook
Good Point John : "I'd just add that the most common (legitimate!) use for friend classes may be testing" :).
mahesh
+1  A: 

Friendship is used when you have multiple classes and/or functions that work together to provide the same abstraction or interface. The classic example is implementing some kind of numerical class, and all the non-member operator functions (*, -, +, <<, etc) are given friendship so that they can work on the private data of the numerical class.

Such use cases are somewhat rare, but they do exist, and friend is very useful.

Brian Neal
Question was about friend classes not other uses of friend?
abababa22
It's the same idea. You give friendship to functions or classes if they are working together to provide a uniform abstraction.
Brian Neal
+2  A: 

A concrete instance would be a class factory, where you want one class to only be created through another factory class, so you make the constructors private, and the factory class a friend of the produced class.

It's kinda' like a 2" 12-point 3/4"-drive socket - not terribly common, but when you need it, you're awfully glad you have it.

Rob K
This is a great point. Since C++ doesn't have packages (which might be one way you'd implement a Factory in C# or Java), it seems you either have to use a friend Factory, or have a protected constructor, and a child implementation class that is created by the Factory. Friend lets you have a factory with less code in C++.
Ogre Psalm33
A: 

The FAQ's section about friends: here

The FQA's section about friends: here

Two different points of view about friend.

Assaf Lavie
+3  A: 

When you wish that one class (Factory) be responsible for creating instances of another class (Type). You can make the constructor of the Type private and thus make sure that only the Factory can create Type objects. It is useful when you wish to delegate the checks to some other class which could serve as a validator. Just one usage scenario.

P.S. Really missing the "friend" keyword in C#...

User
A: 

I always ( and only ) use friend for unit testing private methods. The only other way I can imagine to do this would be to load up the public interface with a whole lot of testing methods, which is just too messy and so I prefer to hide the test methods in a seperate test class.

Something like this:

class cMyClassTest;

class cMyClass
{
public:
.....

private:
friend cMyClassTest;
int calc();  // tricky algorithm, test carefully

};

class cMyClassTest
{
public:
int test_calc()
{
    cMyClass test;
    ....
    int result = test.calc();

    if( result == 42 )
     return 1;
    return 0;
}
};
ravenspoint
A: 

friend class mean we all know that is acesss the value of variable from other class so it is mainly used for use the values so we no need to return the value of other class to main function then main to needed class member function but it having the problem that is a class is friend for other class then friend class should be in below of that class

dhivya