Kundan Kumar
Kundan Kumar

Reputation: 2002

Friend functions in C++

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.

Upvotes: 14

Views: 1043

Answers (5)

BugShotGG
BugShotGG

Reputation: 5190

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.

Upvotes: 0

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.

Upvotes: 2

Bo Persson
Bo Persson

Reputation: 92231

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.

Upvotes: 2

Brandon Kreisel
Brandon Kreisel

Reputation: 1636

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

Upvotes: 4

Jerry Coffin
Jerry Coffin

Reputation: 490098

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.

Upvotes: 20

Related Questions