tags:

views:

957

answers:

7

I see a lot of people recommending a function/class to be made a friend of another class here in SO though there are other alternatives. Shouldn't friend be sparingly used in C++? I feel other options must be considered before deciding on using the friend feature. Opinions/suggestions are welcome.

+4  A: 

Without specific examples this is hard to decide. While friend isn't strictly necessary it does have its uses. If, as you claim, there are better alternatives then obviously use them, by simple definition of the word “better”. Or maybe the decision which solution is better isn't that clean-cut after all.

Personally, I prefer to avoid it when possible but I prefer to use it over method duplication: for example, I do not like to write a print method just to avoid making operator << a friend because I don't see the benefit of the duplicate method.

Konrad Rudolph
+2  A: 

I agree. The friend keyword should be used sparingly.

It may be useful if you have a set of classes that interact together when you want to expose a clean api from those classes to users, but when the classes can interact with each other using a richer interface.

Eg:

class Folder
{
public:
  int GetFileCount();
private:
  void IncrementFileCount();  // users of this class have no right to use this

  friend class File;
};

class File
{
public:
  File(string name, Folder& containingFolder)
  {
     containingFolder.IncrementFileCount(); // except for indirectly when they create a file
  }
};
Scott Langham
+6  A: 

Some say friend is a violation of encapsulation. In my opinion, it is the exact contrary. Without friend, we would end up with either:

  • huge monolithic classes, that does plenty of things they were not meant to, just to avoid letting outer classes access their internals
  • badly encapsulated classes: to separate concerns and write classes with one and only one responsability, we would need to provide public access to internal data needed by the related set of classes.

friend is a good way to overcome this issue, since it lets you free to separate responsabilities in several classes, while at the same time letting you restrict access to implementation details to the few functions or types which need them.

Luc Touraille
+1  A: 

For all those who thinks friend violates the encapsulation, here is what Bjarne Stroustup has to say .

But I personally don't use friend unless it is inevitable. Scenarios like implementation of Iterator patterns there is no other choice.

Friend is friend if used properly otherwise he is enemy!

aJ
+1  A: 

You can also check here: Does friend violate encapsulation

Naveen
A: