Skip to main content

Need of friend function

Short answer

A friend function is a non-member function granted access to private members, declared with friend keyword. Needed to access private data of two or more classes in one function, or overload operators where left operand is not an object (e.g., cout << obj). It takes objects as arguments, not called through object.

Why do we need friend function? Explain with example.

A friend function is a non-member function that is allowed to access the private and protected members of a class. It is declared inside the class with the keyword friend, but it is defined outside like an ordinary function, without the scope operator and without being called through an object.

Why it is needed

  1. To operate on private data of two or more different classes with one function (e.g. add or compare values from two classes).
  2. To overload operators when the left operand is not an object of the class, e.g. cout << obj or 5 + obj.
  3. To let a function outside the class use private data when making it a member is not suitable.

Characteristics

  • Not in the scope of the class and not called with obj.f().
  • Takes the objects as arguments and uses obj.member to access data.
  • Has no this pointer. Can be declared in the public or private part.

Example

#include <iostream>
using namespace std;

class B;                          // forward declaration

class A
{
    int x;
public:
    A(int v) { x = v; }
    friend int maxValue(A, B);
};
class B
{
    int y;
public:
    B(int v) { y = v; }
    friend int maxValue(A, B);
};

int maxValue(A a, B b)            // friend of both classes
{
    return (a.x > b.y) ? a.x : b.y;
}

int main()
{
    A a(10);
    B b(25);
    cout << "Larger = " << maxValue(a, b) << endl;   // 25
    return 0;
}

The function maxValue() reads private x of A and private y of B, which would not be possible for an ordinary function.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 4 questions →