What is a friend function in C++ ?
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.
Uses of the friend function
The 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;}
Code explanation
In the code snippet above:
- Lines 3–7: We create a
Circleclass with a private data memberradius. - Lines 9–13: We implement the constructor of
Circleclass. - Lines 15–18: We declare a
friendfunctiondiameter()which accepts the object of theCirclepassed by reference and returns the diameter of the circle. - Line 21: We create an object of
Circleand set its radius value to5.0; - Line 23: We call the
friendfunctiondiameter()to display the diameter of the circle.
Free Resources