Friend
Function in C++
Definition
A friend function in
C++ is a special function that can access private and protected members of a
class, even though it is not part of that class. Normally, private and
protected members of a class can only be accessed by the class's own methods or
its friends. To make a function a friend of a class, we declare it inside the
class definition using the keyword friend
.
Why Do We Use Friend Functions?
We use a friend
function to allow an external function access to private or protected data of a
class without making it a member of that class.
Need for Friend Functions
1.
Access Private Data: Helps an external
function work with private or protected members of a class.
2.
Convenience: Simplifies code by
avoiding the use of getters or setters.
3.
Specialized Use: Useful when an
external function needs a special relationship with the class.
Advantages of Friend Functions
1.
Direct
access to private and protected members of a class.
2.
Simplifies
code by reducing the need for additional public methods.
3.
Increases
flexibility by allowing interaction with multiple classes.
Disadvantages of Friend Functions
1.
Breaks
encapsulation by exposing private data to external functions.
2.
Introduces
tight coupling, making maintenance harder.
3.
Friendship
is not inherited, so it must be declared for child classes explicitly.
Example of a Friend Function
include<iostream>
using namespace std;
class abc {
private:
int sal = 40000;
protected:
int pm = 5000;
public:
friend void show( abc &obj);
};
void show(abc &obj) {
cout << "Salary is " << obj.sal <<endl;
cout<<"Pocket Money is " << obj.pm << endl;
}
int main() {
abc o1;
show(o1);
return 0;
}
How Friend Functions Work?
- Declared as a
friend
inside the class. - Defined outside the class.
- Accesses private and protected
members using an object of the class.
Keep in mind at the time of interview:
- Friendship is not mutual.
- Friendship is not transitive.
- Friendship is not inherited by
derived classes.
Real-Life Example
A house with locked
rooms (private data) can only be accessed by the owner (class methods).
However, the owner can give a trusted friend like me its Ajay Wadekar Sir
(friend function) a key to access the rooms when needed.
When to Avoid Friend Functions?
1.
If
getters and setters can achieve the same result.
2.
Overusing
friend functions can harm code design and violate encapsulation.
#Happy Coding by AJAY WADEKAR
Comments
Post a Comment