Thursday, 9 April 2020

Write a Program to swap private data members of classes named as class_1, class_2 using friend function.

#include<iostream.h>
#include<conio.h>
class class_2;
class class_1

int value1;
public: 
void indata(int a) 

value1=a; 

void display(void) 

cout<<value1<<"\n"; 

friend void exchange(class_1 &, class_2 &);
};
class class_2

int value2;
public: 
void indata(int a) 

value2=a; 

void display(void) 

cout<<value2<<"\n"; 

friend void exchange(class_1 &, class_2 &);
};
void exchange(class_1 &x, class_2 &y)

int temp = x.value1; 
x.value1 = y.value2; 
y.value2 = temp;
}
int main()

class_1 C1; 
class_2 C2;
C1.indata(100); 
C2.indata(200); 
cout<<"Values before exchange"<<"\n";
C1.display(); 
C2.display(); 
exchange(C1, C2); 
cout<<"Values after exchange"<<"\n"; 
C1.display(); 
C2.display(); 
return 0;

1 comment:

  1. #include
    using namespace std;
    class Child;
    class Parent
    {
    int num1;
    public:
    Parent(int n)
    {
    num1=n;
    }
    void show()
    {
    cout<<"Value of Number 1 : "<<num1;
    }
    friend void swap(Parent &, Child &);
    };

    class Child
    {
    int num2;
    public:
    Child(int n)
    {
    num2=n;
    }
    void show()
    {
    cout<<"Value of Number 2 : "<<num2;
    }
    friend void swap(Parent &, Child &);
    };
    void swap(Parent &x, Child &y)
    {
    int temp = x.num1;
    x.num1 = y.num2;
    y.num2 = temp;
    }
    int main()
    {
    Parent p1(100);
    Child c1(200);
    cout<<"Before Swapping: "<<endl;
    p1.show();
    cout<<endl;
    c1.show();
    swap(p1,c1);
    cout<<endl;
    cout<<"After Swapping: "<<endl;
    p1.show();
    cout<<endl;
    c1.show();
    return 0;
    }

    ReplyDelete