Friend Function and Friend Class
Friend function क्या है?
Private members सामान्यतः बाहरी code के लिए वर्जित होते हैं। Friend function एक अपवाद है: एक non-member function जिस पर class स्पष्ट रूप से भरोसा करती है, उसे private और protected members तक पहुँच देते हुए। Class इसे friend keyword से declare करती है।
Friends क्यों हैं
कभी कोई function जो member नहीं है फिर भी वाकई internals चाहता है — जैसे दो objects की तुलना करने वाला operator, या एक helper जो दो अलग classes का private data पढ़े। सबके लिए data public बनाने के बजाय, class केवल उस एक function को पहुँच देती है।
एक चलता उदाहरण
#include <iostream>
using namespace std;
class Account {
double balance = 1000; // private
friend void show(const Account &a); // access dein
};
void show(const Account &a) { // member nahi
cout << "Balance: " << a.balance << "\n"; // private padh sakta hai
}
int main() {
Account acc;
show(acc); // normal function ki tarah call
return 0;
}Balance: 1000
ध्यान दें show अपने आप call होता है — acc.show() नहीं — क्योंकि यह member नहीं है।
Friend classes
पूरी class friend हो सकती है, तो उसके सभी methods दूसरे के private members तक पहुँच सकते हैं:
class Engine {
int power = 200;
friend class Car; // Car, Engine ke privates dekh sakti hai
};
class Car {
public:
void showPower(const Engine &e) { cout << e.power; }
};Friend बनाम member function
| Member function | Friend function | |
|---|---|---|
| Class का है? | हाँ | नहीं |
| Call ऐसे | obj.f() | f(obj) |
this है? | हाँ | नहीं |
| Privates access? | हाँ | हाँ (दी गई) |
संक्षिप्त syntax उदाहरण और operator इस्तेमाल के लिए, friend function syntax reference देखें।
Friends कब इस्तेमाल करें
- ऐसे operators जिन्हें दोनों operands का private data चाहिए (जैसे
operator<<)। - दो घनिष्ठ संबंधित classes जहाँ एक को दूसरे के internals पढ़ने हों।
- केवल तब जब member function या public getter इतनी साफ़ तरह फिट न बैठे।
Friendship encapsulation में जानबूझकर एक छेद है। कुछ friends ठीक हैं; बहुत सारे design की गंध हैं।
आम गलतियाँ
- Friend function को
obj.f()की तरह call करना — यह member नहीं है। - Friendship को mutual या inherited मानना (यह न कोई है)।
- Friends का अति-इस्तेमाल करके चुपचाप encapsulation नष्ट करना।
- Class के अंदर
frienddeclaration भूलना।
एक Distance class लिखें जो metres private रखे, और एक friend function add(const Distance&, const Distance&) जो उनका योग लौटाए। पुष्टि करें कि यह दोनों objects के private metres पढ़ सकता है।
सारांश
- Friend function एक non-member है जिसे private members तक पहुँच दी गई।
- Class के अंदर
friendसे declare, बाहर परिभाषित। - Normal function की तरह call, object पर नहीं; इसके पास
thisनहीं। - Friend class अपने सभी methods के साथ पहुँच साझा करती है।
- Friendship mutual या inherited नहीं — कम इस्तेमाल करें।
अक्सर पूछे जाने वाले प्रश्न (FAQ)
C++ में friend function क्या है?
friend keyword से declare करते हैं, पर यह बाहर परिभाषित होता है और member function की तरह object पर call नहीं होता।