Sunday, April 6, 2014

C++ Program to swap two integers using friend function

C++ Program to swap two integers using friend function

In object-oriented programming, a friend function that is a "friend" of a given class is allowed access to private and protected data in that class that it would not normally be able to as if the data was public. Normally, a function that is defined outside of a class cannot access such information. Declaring a function a friend of a class allows this, in languages where the concept is supported.
                                                                                         wiki

#include<iostream.h>
class b;
class a
{
int x1;
public:
void reada()
{
cout<<"Enter x1 value\n";
cin>>x1;
}
friend void swap (a &,b &);
};
class b
{
int x2;
public:
void readb()
{
cout<<"Enter an x2 value\n";
cin>>x2;
}
friend void swap (a &,b &);
};
void swap (a &o1, b &o2)
{
int t;
cout<<"Before swapping\nx1="<<o1.x1<<"\n"<<"x2="<<o2.x2<<"\n";
t=o1.x1;
o1.x1=o2.x2;
o2.x2=t;
cout<<"After swapping\nx1="<<o1.x1<<"\n"<<"x2="<<o2.x2<<"\n";
}
void main()
{
clrscr();
a a;
a.reada();
b b;
b.readb();
swap(a,b);
}

No comments:

Post a Comment