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 function
friend 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 Circle class with a private data member radius.
  • Lines 9–13: We implement the constructor of Circle class.
  • Lines 15–18: We declare a friend function diameter() which accepts the object of the Circle passed by reference and returns the diameter of the circle.
  • Line 21: We create an object of Circle and set its radius value to 5.0;
  • Line 23: We call the friend function diameter() to display the diameter of the circle.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved