Friend Function and Friend Class
1. Friend Function
A friend function is a non-member function that can access the private members of a class.
#include <iostream>
using namespace std;
class A {
int x = 10;
public:
friend void show(A obj);
};
void show(A obj) {
cout << "x = " << obj.x;
}
int main() {
A obj;
show(obj);
return 0;
}Output:
x = 102. Friend Class
A friend class can access the private members of another class.
#include <iostream>
using namespace std;
class B;
class A {
int x = 10;
friend class B;
};
class B {
public:
void show(A obj) {
cout << "x = " << obj.x;
}
};
int main() {
A a;
B b;
b.show(a);
return 0;
}Output:
x = 10Simple Difference
| Friend Function | Friend Class |
|---|---|
| Gives access to one function | Gives access to all member functions of a class |
Declared using friend inside a class | Declared using friend class |
Example: friend void show(A); | Example: friend class B; |
No comments:
Post a Comment