Experiment No 8 - Friend Function in C++
Experiment No 8 - Friend Function in C++
Requirements:
Theoretical Description:
Program 1:
#include<iostream.h>
#include<conio.h>
using namespace std;
class temp
{
int x, y, q;
public:
void input()
{
cout << "Enter Two Numbers :";
cin >> x>>y;
}
friend void swap(temp &t);
void display()
{
cout << "After Swap x is :" << x;
cout << "After Swap y is :" << y;
}
};
void swap(temp &t)
{
t.q = t.x;
t.x = t.y;
t.y = t.q;
}
int main()
{
temp t1;
t1.input();
swap(t1);
t1.display();
return 0;
}
Output:
Enter Two Numbers : 20 30
After Swap x is : 30
After Swap y is : 20
Program 2:
#include<iostream>
using namespace std;
class Derived;
class Base
{
protected:
int num1;
public:
Base()
{
num1=10;
}
void show()
{
cout<<"\n Value of Number 1 : "<<num1;
}
friend void swap(Base *num1, Derived *num2);
};
class Derived
{
protected:
int num2;
public:
Derived()
{
num2=20;
}
void show()
{
cout<<"\n Value of Number 2 : "<<num2;
}
friend void swap(Base *num1, Derived *num2);
};
void swap(Base *no1, Derived *no2)
{
int no3;
no3=no1->num1;
no1->num1=no2->num2;
no2->num2=no3;
}
int main()
{
Base b;
Derived d;
swap(&b, &d);
b.show();
d.show();
return 0;
}
Output:
Program 3:
#include<iostream>
class SwapNumbers
private:
int x,y;
public:
void getdata()
cin>>x>>y;
void showdata()
cout<<"X="<<x<<"Y="<<y;
};
/* Friend function to swap two numbers*/
void swap(SwapNumbers&s)
int temp;
temp=s.x;
s.x=s.y;
s.y=temp;
int main()
SwapNumbers s;
s.getdata();
Page | 10
cout<<endl<<"Before swapping:"<<endl;
s.showdata();
swap(s);
cout<<endl<<"After swapping:"<<endl;
s.showdata();
return 0;
Program 4:
#include
<iostream>
using namespace std;
class b;
class a
{
int x;
public:
a(int c)
{
x=c;
}
friend void swap(a,b);
};
class b
{
int y;
public:
b(int d)
{
y=d;
}
friend void swap(a,b);
};
void swap(a e,b f)
{
int temp;
temp=e.x;
e.x=f.y;
f.y=temp;
cout<<"after swapping value of class a="<<e.x<<endl;
cout<<"after swapping value of class b="<<f.y<<endl;
}
int main() {
a e(5);
b f(3);
swap(e,f);
return 0;
}
Program 5:
#include <iostream.h>
#include <conio.h>
class Second;
class First
{
private:
int x;
public:
void value1(int);
void display1();
friend void swap(First s1,Second s2); //friend function
};
void First::value1(int a)
{
x=a;
}
void First::display1()
{
cout<<x;
}
class Second
{
private:
int y;
public:
void value2(int);
void display2();
friend void swap(First s1,Second s2); //friend function
};
void Second::value2(int b)
{
y=b;
}
void Second::display2()
{
cout<<y;
}
void swap(First s1,Second s2) //friend function definition
{
int t;
t=s1.x;
s1.x=s2.y;
s2.y=t;
cout<<"Final values of class 1 after swapping (x) = "<<s1.x;
cout<<endl;
cout<<"Final values of class 2 after swapping(y) = "<<s2.y;
cout<<endl;
}
void main()
{
First f;
Second s;
f.value1(9);
s.value2(15);
cout<<"Initial values of class 1 (x) = ";
f.display1();
cout<<endl;
cout<<"Initial values of class 2 (y) = ";
s.display2();
cout<<endl;