Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between friend function and friend class?

what is the difference between friend function and friend class? and where should be use of friend keyword?

like image 629
ankit Avatar asked Sep 25 '10 08:09

ankit


3 Answers

In short, one is a class and one is a function. For the function, just that one function gets access to private members. For a class, the whole class and all its functions get access to the private members of the befriended class.

The friend keyword is used to grant access to private data members. At times you may need a helper class or a complimentary class to access the private members of a different class. For functions, a common example is an operator overload. Perhaps you want to overload the + operator. You may make an operator+ function declared outside the class (so it can be called without an object) and it will need to access the private class data.

Check out this site for a detailed description of both and how to use them.

like image 59
JoshD Avatar answered Sep 21 '22 00:09

JoshD


Friend function

  1. The friend keyword is used for declaration.
  2. While writing definition of function, the friend keyword is not required.
  3. Through a friend function, we can allow outside functions to access the class members.

Friend class

  1. For the declaration of a friend class, the friend keyword is used: friend class a;
  2. While writing a class, the friend keyword is not required.
  3. With a friend class we can access the members of one class into another.
like image 20
Prashant Kumbharkar Avatar answered Sep 20 '22 00:09

Prashant Kumbharkar


A friend function is used for accessing the non public member of a class.A class can allow non-member function and other classes to access its own private data by making them friend A Friend class has full access of private data members of another class without being member of that class.

like image 38
chandan Kumar Avatar answered Sep 21 '22 00:09

chandan Kumar