14

I have a doubt related to friend functions in C++. Friend function is not a member function of the claas and can be invoked directly from the main. So, what difference does it make if we keep the friend function within the private or the public part of the class. I have generally noticed that the friend functions are always in the public part. In what scenario we should keep the friend function within private.

iammilind
  • 68,093
  • 33
  • 169
  • 336
Kundan Kumar
  • 1,974
  • 7
  • 32
  • 54
  • 1
    I don't know why this is getting close votes... This is a perfectly sensible (if poorly worded) question. – ildjarn Jun 19 '12 at 19:19
  • +1 - "when is it good design to make a private friend function" is a perfectly fine question. (Or why is it never.) – djechlin Jun 19 '12 at 19:19
  • 5
    "Friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords." - http://en.wikipedia.org/wiki/Friend_function –  Jun 19 '12 at 19:21

5 Answers5

20

The compiler does not pay any attention to whether a friend function is in the private or public (or protected) section of a class. Most people put it in the public section, but it'll be publicly visible regardless of where you put it.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
4

It does not matter if you declare it in the public: or private: part of the class. It will function the same regardless.

Brandon Kreisel
  • 1,596
  • 1
  • 17
  • 23
2

One reason for having the friend declarations in the private section is that it can keep them together with the member functions or objects they are supposed to have access to.

Other than that, there is no difference.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
2

The friend keyword is just here to grant private access to another function which is not part of your class. Since it's not part of your class, it's not affected by public/private specifiers.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Frédéric Terrazzoni
  • 2,190
  • 19
  • 25
0

it doesn’t matter where you put the friendship declaration. It may exists inside any of the class parts (public, private or protected) but must be put outside any function or aggregate.

Here is a nice example and explanation from www.cprogramming.com:

It is often useful for one class to see the private variables of another class, even though these variables should probably not be made part of the public interface that the class supports. For instance, if you were writing a binary tree, you might want to use a Node class that has private data, but it would still be convenient for the functions that actually combine nodes together to be able to access the data directly without having to work through the Node interface. At times, it may not even be appropriate for an accessor function to ever give even indirect access to the data.

BugShotGG
  • 5,008
  • 8
  • 47
  • 63