-->

Friend Function (swap members)




Friend Function


Swap two members in class using Friend Functions

if you want to download the .cpp file then simple click on the link below to download.

GET FILE

How to download .cpp file



[01]  We will add the header files in the program.


#include<iostream>

using namespace std;


[02]  After that we will create class of name swaping


class swaping

{

private:///access specifier

int x;///declaring data type for x

int y;///declaring data type for y

public:///access specifier

void input()///function for input of data 

{

cout<<"enter values"<<endl;///getting data from the user

cout<<"a = ";cin>>x;///getting data from the user

cout<<"b = ";cin>>y;///getting data from the user

cout<<"befor swaping A = "<<x<<" and B = "<<y<<endl;///showing old data

}

void output()///function for output of data

{

cout<<"After swaping A = "<<x<<" and B = "<<y<<endl;///showing new data

}

friend void swap (swaping &s);///creating friend function

};


[03]  After that create a function for constructer 


void swap(swaping &s)///friend function to swap values

{

int z;///declaring 3rd variebles tp swap easily

z = s.x;///processing

s.x = s.y;///processing

s.y = z; ///processing

}


[04] And finally create the main function and call the functions and class by reference (only functions)


int main()////start of main function

{

swaping s;////creating objects of class

s.input();////calling functions by reference

swap(s);////calling functions by reference

s.output();////calling functions by reference

return 0; ////ENDL;

}

if you want to download the .cpp file then simple click on the link below to download.

GET FILE


must let your thoughts.

created by Syab Ahmad Shah.