📘 Lesson  ·  Lesson 68

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

Summary

  • A friend function/class can access private members of a class.
  • Declared with the friend keyword 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

सारांश

  • A friend function/class can access private members of a class.
  • Declared with the friend keyword inside the class.
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.