what is the difference between friend function and friend class?

19,205

Solution 1

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.

Solution 2

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.

Solution 3

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.
Share:
19,205
ankit
Author by

ankit

Updated on June 04, 2022

Comments

  • ankit
    ankit about 2 years

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

  • sbi
    sbi almost 14 years
    +1 for finding more to say about this than the first sentence. I would have utterly failed on that.