what is a friend function in c++

1 year ago 58
Nature

A friend function in C++ is a function that is declared outside a class but is capable of accessing the private and protected members of the class. It is used when two classes need to share their members, such as data members, class functions, or function templates. A friend function can be implemented in two ways: as a method of another class or as a global function.

Features of friend functions include:

  • A friend function is a non-member function or ordinary function of a class, which is declared as a friend using the keyword “friend” inside the class. By declaring a function as a friend, all the access permissions are given to the function.
  • The keyword “friend” is placed only in the function declaration of the friend function and not in the function definition or call.
  • A friend function is able to access members without the need of inheriting the class.
  • Friend functions are not considered class members; theyre normal external functions that are given special access privileges.

Advantages of friend functions include:

  • A friend function allows the programmer to generate more efficient codes.
  • It allows the sharing of private class information by a non-member function.
  • It accesses the non-public members of a class easily.
  • It is widely used in cases when two or more classes contain the interrelated members relative to other parts of the program.

In summary, a friend function in C++ is a function that can access the private and protected members of a class and is declared outside the class. It is used to share members between two classes and can be implemented as a method of another class or as a global function. Friend functions have several advantages, including more efficient code generation and easy access to non-public members of a class.