What is Friend Function in C++?
In C++, private data is hidden. No outside function can access it. But sometimes we want one special outside function to access private data. That special function is called Friend Function.
Think like this: Your house is private, but your best friend is allowed to come inside. Same way, Friend Function is not a member of class, but class allows it to access its private data.
How to Declare Friend Function?
We write friend keyword inside the class.
Example of Friend Function:
include
using namespace std;
class Box {
private:
int length;
public:
Box() {
length = 10;
}
// Friend Function Declaration
friend void showLength(Box b);
};
// Friend Function Definition
void showLength(Box b) {
cout << "Length is: " << b.length << endl;
}
int main() {
Box b1;
showLength(b1);
return 0;
}
Output:
Length is: 10
Here showLength is not a member of Box class, but still it can access private length because it is a friend.
Important Points of Friend Function:
- Friend Function is not a member of class.
- It is declared inside class with friend keyword, but defined outside.
- It can access private and protected members.
- It is called like normal function, not with object like b.showLength().
Friend Function with Two Classes Example:
Sometimes one function needs private data of two classes. Then we make it friend of both classes.
include
using namespace std;
class B;
class A {
private:
int num1;
public:
A() { num1 = 5; }
friend int add(A, B);
};
class B {
private:
int num2;
public:
B() { num2 = 10; }
friend int add(A, B);
};
int add(A a, B b) {
return a.num1 + b.num2;
}
int main() {
A a;
B b;
cout << "Sum is: " << add(a, b);
return 0;
}
Output:
Sum is: 15
Conclusion:
Friend Function breaks encapsulation a little, but it is useful when two classes need to share private data. Use it only when really needed.
I have tested this code myself and it works perfectly.
Top comments (0)