- 2074 Chaitra · 6 marks
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
- Forward-declare the second class (
class B;) because the first class's function uses it as a parameter. - Define the first class
Awith the function declared only. - Define class
Bwith the friend declaration usingA::function. - Define
A::functionafterBis 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)
Related questions
- Friend class and encapsulation · Object Oriented Programming, chapter 4
- Need of friend function · Object Oriented Programming, chapter 4 · asked 2×
- Static data member and member function · Object Oriented Programming, chapter 4 · asked 3×
- Binary operator member function one argument · Object Oriented Programming, chapter 5
- Overloading via member and non-member function · Object Oriented Programming, chapter 5
- Member function overriding with virtual function · Object Oriented Programming, chapter 7
- Insert a string into another string · Computer Programming, chapter 7
- Euler's formula: one end fixed, other hinged · Strength of Materials, chapter 8 · asked 2×
- Event management system summary and class diagram · Object Oriented Analysis and Design, chapter 2
- Unequal angle tension member with HSFG bolts · Design of Steel and Timber Structure, chapter 5