Pre-requisite: Friend Function
CASE 1:
Given two numbers a & b, swap these two numbers using the friend function of C++.
Examples:
Input : a = 5, b = 9
Output : a = 9, b = 5
Input : a = 4, b = 6
Output : a= 6, b = 4
Approach:
Create a class Swap, declare three variables in it, i.e., a, b, and temp and create a constructor for inputs. Declare a friend function in it. Define the friend function outside the class scope by taking arguments as call by reference to pass the copy of Swap Object. Perform the swap operation with Swap variables.
C++
#include <iostream>
using namespace std;
class Swap {
int temp, a, b;
public :
Swap( int a, int b)
{
this ->a = a;
this ->b = b;
}
friend void swap(Swap&);
};
void swap(Swap& s1)
{
cout << "\nBefore Swapping: " << s1.a << " " << s1.b;
s1.temp = s1.a;
s1.a = s1.b;
s1.b = s1.temp;
cout << "\nAfter Swapping: " << s1.a << " " << s1.b;
}
int main()
{
Swap s(4, 6);
swap(s);
return 0;
}
|
Output: Before Swapping: 4 6
After Swapping: 6 4
CASE 2:
Given two objects s1 & s2 of a class, swap the data members of these two objects using friend function of C++.
Examples:
Input : a = 6, b = 10
Output : a = 10, b = 6
Input : a = 4, b = 6
Output : a= 6, b = 4
Approach:
Create a class Swap, declare one variable in it, i.e., num and create a constructor for inputs. Declare a friend function in it. Define the friend function outside the class scope by taking arguments as call by reference to pass the copy of Swap Object. Perform the swap operation.
C++
#include <iostream>
using namespace std;
class Swap {
int num;
public :
Swap( int num)
{
this ->num = num;
}
friend void swap(Swap&, Swap&);
};
void swap(Swap& s1, Swap& s2)
{
int temp;
cout << "\nBefore Swapping: " << s1.num << " " << s2.num;
temp = s1.num;
s1.num = s2.num;
s2.num = temp;
cout << "\nAfter Swapping: " << s1.num << " " << s2.num;
}
int main()
{
Swap s1(6), s2(10);
swap(s1,s2);
return 0;
}
|
Output: Before Swapping: 6 10
After Swapping: 10 6
Time Complexity: O(1)
Auxiliary Space: O(1)