📘 Lesson · Lesson 68
Friend Function & Class
Friend Function & Class
What is a Friend Function?
💡 Note
A friend function is not a member of a class but is allowed to access its private and protected members.
Example
C++
#include <iostream>
using namespace std;
class Box {
int width = 10;
friend void show(Box b); // friend declaration
};
void show(Box b) {
cout << "Width: " << b.width; // can access private
}
int main() { show(Box()); return 0; }Output:
Width: 10
Width: 10
Summary
- A friend function/class can access private members of a class.
- Declared with the
friendkeyword inside the class.
a Friend Function क्या है?
💡 Note
A friend function is not a member of a class but is allowed to access its private and protected members.
Example
C++
#include <iostream>
using namespace std;
class Box {
int width = 10;
friend void show(Box b); // friend declaration
};
void show(Box b) {
cout << "Width: " << b.width; // can access private
}
int main() { show(Box()); return 0; }Output:
Width: 10
Width: 10
सारांश
- A friend function/class can access private members of a class.
- Declared with the
friendkeyword inside the class.
💻 Live Code Editor
Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें.
Agar load na ho to naye tab mein kholें.