Skip to main content

Member function as friend of another class

Short answer

To make a member function a friend, forward-declare the second class, define the first class with the function declaration only, then in the second class declare it as friend using scope resolution, e.g., friend int First::func(Second&);. Finally, define the function after both classes to access private members.

Explain how any member function of a class can be friend of other class with a suitable example.

A single member function of one class can be made a friend of another class instead of making the whole class a friend. In the second class we declare it as:

friend return_type FirstClass::function(args);

This gives only that function access to the private members of the second class.

Steps

  1. Forward-declare the second class (class B;) because the first class's function uses it as a parameter.
  2. Define the first class A with the function declared only.
  3. Define class B with the friend declaration using A::function.
  4. Define A::function after B is complete, since it needs to access B's members.

Example

#include <iostream>
using namespace std;

class B;                              // forward declaration

class A
{
    int a;
public:
    A(int v = 0) { a = v; }
    int sum(B &b);                    // declared only
};

class B
{
    int b;
public:
    B(int v = 0) { b = v; }
    friend int A::sum(B &);           // only A::sum is a friend
};

int A::sum(B &obj)                    // defined after B
{
    return a + obj.b;                 // accesses private b of B
}

int main()
{
    A x(10);
    B y(5);
    cout << "Sum = " << x.sum(y) << endl;   // 15
    return 0;
}

Only A::sum() can access b. Other members of A cannot, which is the difference from a friend class. Friendship is granted by B, not taken by A.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 4 questions →