1

What is the real use of a friend function/class in C++? Could you give an example where only friend is the right approach?

Thanks

curiousguy
  • 8,038
  • 2
  • 40
  • 58
Sanish
  • 1,699
  • 1
  • 12
  • 21
  • 1
    See those questions on the right-hand-side of the page? Click through a few of them. They are relevant. – Blender Dec 23 '11 at 05:13
  • 1
    Yes, got a good one here : http://stackoverflow.com/questions/17434/when-should-you-use-friend-in-c. I should have done some more research before posing my question, sorry :-( – Sanish Dec 23 '11 at 05:29
  • Extending the public interface and Documenting coupling: http://programmers.stackexchange.com/a/99595/12917 – Martin York Dec 23 '11 at 06:06
  • Unlike enemies - you need to keep your friends closer. Stay clear of friends and do not trust them with your assets (BTW That was a metaphor for the Americans around here) – Ed Heal Dec 23 '11 at 06:39

3 Answers3

8

"In C++, only your friends can access your private parts."

The point of a friend is that you can package your software into smaller groupings, like friend classes etc, while still allowing access to the internals of a class. This arguably lets you maintain finer control on encapsulation than without friending.

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
0

i think often friend function usage its a matter of readability. For example next overloaded operator looks symmetrically and this may be good for code reader.

friend const X operator+(const X&, const X&);

inline const X operator+(const X& arg1, const X& arg2)
{
    X r;
    r.x = arg1.x + arg2.x;
    return r;
}

But main point its their ability to access private data of two different classes.

Yola
  • 18,496
  • 11
  • 65
  • 106
-2

Using friend is actually very discouraged in C++ (it kinda breaks the whole encapsulation idea), but it comes to my mind an example where only friend is the right approach:

friend ostream & operator<< (ostream & out, const MyClass & C);
friend istream & operator>> (istream & in, MyClass & C);
juliomalegria
  • 24,229
  • 14
  • 73
  • 89
  • 1
    Why are things different with input and output operators? If you're going to give the user the ability to read/write the class data from/to a stream, why not give them public accessors to the data? Then the operators don't need to be friends, since they can call the public accessors. – Benjamin Lindley Dec 23 '11 at 05:49
  • 1
    friendship increases encapsulation. – Martin York Dec 23 '11 at 06:08
  • there are plenty of cases where you want the class to have iostream behaviour, but you don't want to give public accessors to some attributes. It may sound contradictory.. because it is, and that's why `friend` is discouraged. – juliomalegria Dec 23 '11 at 06:10
  • @LokiAstari: how could friendship increase encapsulation? It decrease encapsulation at any point of view. Encapsulation means _restricting access to some classes components_. Using `friend`, you ignore that restricted part of a class, so, it goes against encapsulation. – juliomalegria Dec 23 '11 at 06:16
  • @julio.alegria: -1 from me. Totally disagree that friendship is discouraged (and if you search this site for C++ friendship you will find the consensus disagrees with your statement that it decreases encapsulation: http://stackoverflow.com/questions/1093618/how-does-the-friend-keyword-class-function-break-encapsulation-in-c). But don't take that to mean you should use it for everything (as with all language features use as required). – Martin York Dec 23 '11 at 06:18
  • 1
    @julio.alegria: It increases encapsulation because it reduces your need to expose your internal implementation in general. Though you are exposing you internals yo your friends (and thus tightly couple yourself to your friend) this will reduce the need to expose your internal implementation to non friends (ie people that are not part of your public interface) this reduces overall coupling and thus increases encapsulation. – Martin York Dec 23 '11 at 06:25
  • @LokiAstari I think we have to differentiate between the OOP encapsulation concept and the C++ twisted encapsulation concept (not the same, not the same at all). In the OOP encapsulation concept, **nobody** except the class can access its attributes, so, following this concept, `friend` is bad, very bad for encapsulation. – juliomalegria Dec 23 '11 at 06:30
  • @julio.alegria: The general consensus in the C++ community is that it is good for encapsulation. The highest scoring answers to most question see to support this: http://stackoverflow.com/a/734114/14065 http://stackoverflow.com/a/1093681/14065 http://stackoverflow.com/a/17443/14065 http://stackoverflow.com/a/17505/14065 – Martin York Dec 23 '11 at 06:35
  • @LokiAstari I'm going to use a cliché here: "we agree to disagree" – juliomalegria Dec 23 '11 at 06:43
  • "_Using friend is actually very discouraged in C++_" Wrong. – curiousguy Dec 23 '11 at 06:48
  • @julio.alegria: Friend functions do decrease encapsulation. But in exactly the same way that public methods decrease encapsulation. There is not difference between the two. – Martin York Dec 23 '11 at 06:59
  • @curiousguy No, it shows there is disagreement between software engineers; this in no way implies it is some voodoo cult. – Alice Jul 29 '14 at 11:29
  • @Alice "encapsulation" is actually a voodoo cult. – curiousguy Jul 30 '14 at 06:37
  • @curiousguy Please, do explain how a widely used and accepted practice is voodoo or cultish. – Alice Aug 01 '14 at 20:50
  • @Alice It's a long story. For a start, the textbook examples of encapsulation (complex numbers) are all wrong; you want none of it. In general, building bricks should expose how they work. You want your string class to expose the fact it uses refcount, or that it doesn't. You don't want unpredictable performances. This is basic engineering. Tools should have document behaviour and performances. Hiding the performance is very wrong. CS is not math. Performance matters. Significant changes to the implementation of a building block is wrong. – curiousguy Aug 02 '14 at 00:20
  • @curiousguy Your statements are not merely wrong; they are categorically so. An ADT should not expose how it works, it should merely expose it's algorithmic complexity (preferably in Big O). A basic fact of engineering is that new techniques come along with frightening regularity. By exposing only necessary and sufficient information, newer and better algorithms can be seamlessly substituted when they are discovered. Predictable performance has nothing to do with exposing unnecessary information; that's why we have formalizations like big O. CS IS math, just like geometry. – Alice Aug 02 '14 at 01:04
  • @Alice "new techniques come along with frightening regularity" can you name one? – curiousguy Aug 02 '14 at 01:29
  • @curiousguy Allow me to name several: skip lists (1990), unrolled linked lists (1994), funnel sort (1999), soft heaps (2000/2009), distributed hash tables (2001), AKS primality test (2002), block chains (2009), Counter-based parallel random number generators (2011), ctries (2011), HElib (homomorphic encryption, 2013), Sparse Fast Fourier Transform (2012-2014). If we are to include the various small enhancements made to data structures and algorithms, I'd say Judy arrays, lock free versions of structures, and the constant enhancements to ropes, finger trees, and hash tables also apply. – Alice Aug 02 '14 at 02:49
  • @curiousguy Many of these structures benefit from being used as ADT's or generic algorithms; funnel sort is *the* sorting algorithm for even moderately large lists, unrolled linked lists and skip lists are drop in replacements that offer the same algorithmic bounds but can be much faster or smaller, SFFT makes many common FFT's faster, lock free structures and ropes offer advantages, etc. But if the building blocks exposed how they worked, you could not drop in new structures easily. That is the point of encapsulation: providing a replaceable and scalable interface. – Alice Aug 02 '14 at 02:58
  • @Alice Homomorphic encryption is a replacement for what? "funnel sort" affect ADT how? Lockfree structures replace locked structures? – curiousguy Aug 02 '14 at 04:02
  • @curiousguy Funnel sort is an algorithm; algorithms are run over ADT's. You asked for new techniques; not all of them are ADT's. Good work cherry picking and then assaulting a straw man. – Alice Aug 02 '14 at 04:19