Swap numbers using Friend Function in C++

C++
Loading...

Swap numbers using Friend Function in C++CPP OOP’s In Hindi – Aaj Ham C++ OOPs Me Ek C++ Swap 2 Numbers Program Ko Create Karne Wale Hai.

Also Read – Classes & Object & Data Members Etc

Swap numbers using Friend Function in C++

C++ Programming Me Class Function Ko Class Ke Bahar Se Access Karne Ke Liye friend Function Ka Istemal kiya Jata Hai, Ye all private and protected members Function Ko Class Me se Access Kar Sakta Hai |

Ise Ham Ek Example Ke Sath Dekhte Hai, Jisme Ham 2 Numbers Ko Swap Karenge |

Example:

#include<iostream>
using namespace std;
class SwapNumbers
{ 
	private:
		int x,y;
	public:
	void getdata()
	{ 
		cin>>x>>y;
	}
	void showdata()
	{
	 cout<<"X="<<x<<"Y="<<y;
	}
	friend void swap(SwapNumbers&s);
};

/* 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;
	cout<<"Input two numbers to swap:";
	s.getdata();
	Page | 10
	cout<<endl<<"Before swapping:"<<endl;
	s.showdata();
	swap(s);
	cout<<endl<<"After swapping:"<<endl;
	s.showdata();
	return 0;
}

Output:

Input two numbers to swap: 10 20
Before swapping
x=10 y=20
After swapping:
x=20 y=10

Also Read – Shopping List Program

Aap Upper Output Ko Dekh Kar Program Ko Understand Kar Sakte Hai, isme Hame Class SwapNumbers Create Kiya And Fir Unke Value Ko Input Karaya Hai, Uske Bad Hame Unhe Print Kar Diya Hai |

Leave a Reply

Your email address will not be published.