Advertisements
Advertisements
प्रश्न
Explain friend function in C++ with example.
कोड लेखन
स्पष्ट करा
Advertisements
उत्तर
- C++ allows a function to be declared as a friend of one or more classes, giving it access to the private data of those classes. Such a function does not have to be a member of any class.
- Normally, a non-member function cannot access the private data of a class. However, when two or more classes need to share a common function, a friend function is used.
- To make an external function a friend of a class, it is declared inside the class definition as shown below:
class class-name { private: ...... ...... public: ...... friend return-type function-name (arguments); //declaration }; - The keyword friend specifies that the function has special access to the class. The function itself is defined like a normal C++ function and does not use the class name, the
friendkeyword, or the scope resolution operator in its definition.
Example:
//Swapping private data of classes using friend function
#include<iostream.h>
#include<conio.h>
class A; //forward declaration
class B
{
private:
int val2;
public:
void getdata (void)
{
val2=21;
)
void display (void)
{
cout<<“Value 2:"<<val2;
}
friend void exchange (B&, A&);
};
class A
{
private:
int val1;
public:
void get (void)
{
val1=12;
}
void disp (void)
{
cout<<"Value 1:"<<val1;
}
friend void exchange (B&, A&);
};
void exchange (B &x, A &y)
{
int temp;
temp = x.val2;
x.val2 = y.val1
y.val1 = temp;
}
void main()
{
A abc;
Bpqr;
abe.get();
par.getdata();
cout<<"Before exchange:-";
abc.disp();
pqr.display();
exchange (pqr, abc); //Swapping
cout<<"\n After exchange:";
abc.disp();
pqr.display( );
}shaalaa.com
या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
2024-2025 (March) Official
