friend function of class in C++

In C++ language we can make a general outside function to friendly function of one or more classes. So that It can access other data members and member functions of class. if any class wants to make a normal function to its friend function then It uses friend keyword before declaration of normal function. In other words "All those functions of class which are declared with friend keyword are called friend function of that class and they have full rights to access other data members and member functions of class."
C++ लैंग्वेज में हम एक सामान्य बाहरी फंक्शन को एक या अधिक क्लासेस का फ्रेंडली फंक्शन बना सकते है जिससे यह उन क्लासेस के अन्य डाटा मेम्बर्स एवं मेम्बर फंक्शन को एक्सेस कर सकता है। यदि कोई क्लास किसी सामान्य फंक्शन को अपन friend बनाना चाहती है तब वह उस फंक्शन के डिक्लेरेशन के पूर्व friend कीवर्ड का प्रयोग करती है। दुसरे शब्दों में "क्लास के वे सभी फंक्शन जिन्हें friend कीवर्ड के साथ डिक्लेअर किया गया है उस क्लास के फ्रेंड फंक्शन कहलाते है एवं इन्हें उस क्लास के अन्य डाटा मेम्बर्स एवं मेम्बर फंक्शन को एक्सेस करने का पूर्ण अधिकार होता है।"  

Characteristics of friend function:- 
फ्रेंडफंक्शन के गुण:-

1. Friend function will not define in a class.
फ्रेंड फंक्शन को क्लास के अन्दर परिभाषित नहीं किया जा सकता है।
2. It is not called by class object because it is a normal function. 
इसे क्लास ऑब्जेक्ट द्वारा कॉल नहीं किया जा सकता है क्योंकि यह एक सामान्य फंक्शन होता है। 
3. Friend function can access data members and member functions of class with class object and dot operator(.).
फ्रेंड फंक्शन, क्लास ऑब्जेक्ट एवं डॉट ऑपरेटर(.) की सहायता से क्लास के अन्य डाटा मेम्बर्स एवं मेम्बर फंक्शन को एक्सेस करता है। 
4. It can be declared in public/private/protected section of class. 
यह क्लास के पब्लिक/प्राइवेट/प्रोटेक्टेड सेक्शन में घोषित किया जा सकता है। 
5. It takes class object as input argument.
यह इनपुट आर्गुमेंट के रूप में क्लास का ऑब्जेक्ट ग्रहण करता है।  

Syntax:- 
with in  a class

friend return_type function_name (arguments);

C++ program for Friend Function -

#include<iostream.h>
#include<conio.h>
class ABC;
class XYZ{
int x;
public:
void setvalue(){
cout<<"enter value of x=";
cin>>x;
}
friend void max(XYZ,ABC);
};
class ABC{
int a;
public:
void setnum(){
cout<<"Enter value of a=";
cin>>a;
}
friend void max(XYZ,ABC);
};
void max(XYZ m,ABC n){
if(m.x>=n.a){
cout<<"max="<<m.x<<" of XYZ class"<<endl;
}
else{
cout<<"max="<<n.a<<" of ABC class"<<endl;
}
}
int main(){
ABC ob1;
XYZ ob2;
clrscr();
ob2.setvalue();
ob1.setnum();
max(ob2,ob1);
getch();
return 1;
}

No comments:

Post a Comment