Advantage and disadvantage friend function C++
Friend Function: -
A friend function in C++ is a function that can access the private, protected, and public members of a class.
In C++, a friend function is a function that is defined outside of a class yet has access to all of the private and protected members of that class. There might be times when two classes need to share programming members.
These members include data members, class functions,
and function templates, to name a few. In such cases, we add the intended functions as a friend to each of these classes, granting access to private and protected data to class members.
Advantage of Friend Function: -
- Like any other function, the friend can be declared anywhere in the code.
- It, like any other function, can be called without the usage of an object.
- Many classes can benefit from the use of a function.
- A friend function is used to access a class's non-public members.
- Friend function enables the creation of more efficient programmes.
- It adds extra functionality to the class that isn't commonly used.
- It allows a non-member function to share private class information with another function.
- It's utilized when two or more classes somehow have members tied to other portions of the program.
Disadvantage of Friend Function: -
- The friend function is not passed down to derived classes.
- Friend functions cannot be specified as static or extern because they lack a storage class specifier.
Conclusion:
Friends are not members' functions, despite the presence of prototypes for friend functions in the class specification.
Friend functions can be declared in any class definition section, whether public, private, or protected.
Friends can be declared in any class definition section, including the public, private, and protected sections.