USE OF FRIEND FUNCTION IN C++

What is a Friend Function?
A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends.


To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend


#include<iostream.h>
#include<conio.h>
class num2;
class num1
{
int x;
public:
void setValue(int i)
{
x=i;
}
friend void swap(num1,num2);
};

class num2
{
int y;
public:
void setValue(int i)
{
y=i;
}
friend void swap(num1,num2);
};

void swap(num1 a,num2 b)
{
int temp;
cout<<"Before Swaping Value"<<endl;
cout<<" X = "<<a.x;
cout<<" Y = "<<b.y;
temp=a.x;
a.x=b.y;
b.y=temp;
cout<<"\nAfter Swaping Value"<<endl;
cout<<" X = "<<a.x;
cout<<" Y = "<<b.y;
}

void main()
{
num1 a;
num2 b;
clrscr();
a.setValue(10);
b.setValue(20);
swap(a,b);
getch();
}


/*
Output:
Before Swaping Value
 X = 10 Y = 20
After Swaping Value
 X = 20 Y = 10
*/

No comments

Post your comments

Powered by Blogger.