- Asked 2/10
- 2074 Chaitra · 2 marks
- 2070 Asar · 4 marks
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
- To operate on private data of two or more different classes with one function (e.g. add or compare values from two classes).
- To overload operators when the left operand is not an object of the class, e.g.
cout << objor5 + obj. - 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.memberto access data. - Has no
thispointer. 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)
Related questions
- Member function as friend of another class · Object Oriented Programming, chapter 4
- Need of virtual function · Object Oriented Programming, chapter 7 · asked 4×
- Need of template; function template overloading · Object Oriented Programming, chapter 9
- Friend class and encapsulation · Object Oriented Programming, chapter 4
- mdistance and edistance addition via friend · Object Oriented Programming, chapter 4
- Operator overloading: need and definition · Object Oriented Programming, chapter 5 · asked 3×
- Why do we need DFT · Digital Signal Analysis and Processing, chapter 7 · asked 6×
- Why do we need FFT · Digital Signal Analysis and Processing, chapter 7 · asked 2×
- Need for difference equation; LCCDE and system function · Digital Signal Analysis and Processing, chapter 1 · asked 2×
- Firewall, its need and types · Computer Networks and Security, chapter 8 · asked 7×