In C++, a friend function is a non-member function that has access to the private and protected members of a class. The friend function is declared inside the class.
friend functionThe friend function can be used in the following ways:
They can be used to overload operators for a class. This can be useful for allowing objects of the class to be used with the standard arithmetic and comparison operators.
They can access the private and protected members of a class, allowing them to perform operations that would not be possible for a regular member function.
They can be used to write testing code that accesses the private data of a class. This can be useful for testing purposes because it allows to inspect the state of objects.
Below is an example of how we may use a friend function to access private data in C++:
#include <iostream>using namespace std;class Circle{private:double radius;public:Circle(double r){radius = r;}// friend functionfriend double diameter(Circle &c){return 2 * c.radius;}};int main() {Circle c(5.0);cout << "The diameter of circle is: " << diameter(c) << endl;return 0;}
In the code snippet above:
Circle class with a private data member radius.Circle class.friend function diameter() which accepts the object of the Circle passed by reference and returns the diameter of the circle.Circle and set its radius value to 5.0;friend function diameter() to display the diameter of the circle.Free Resources