Sunday, May 16, 2021

Friend function in c++ | Friend fuctions class in c++

 


#include<iostream>
using namespace std;
class c2;

class c1{
    int val1;
    friend void exchange(c1 &,c2 &);
    public:
        void inData(int a)
        {
            val1=a;
        }
        void display(){
            cout<<"The value of c1 is "<<val1<<endl;
        }
};

class c2{
    int val2;
    friend void exchange(c1 &,c2 &);
    public:
        void inData(int a)
        {
            val2=a;
        }
        void display(){
            cout<<"The value of c1 is "<<val2<<endl;
        }
};

void exchange(c1 & x,c2 & y)
{
    int tem;
    tem=x.val1;
    x.val1=y.val2;
    y.val2=tem;
}

int main()
{
    c1 oc1;
    c2 oc2;
    oc1.inData(34);
    oc2.inData(88);

    cout<<"Before Exchange"<<endl;
    cout<<"c1 :";
    oc1.display();   
    cout<<"c2 :";
    oc2.display();
    cout<<endl

    exchange(oc1,oc2);

    cout<<"After Exchange"<<endl;
    cout<<"c1 :";
    oc1.display();   
    cout<<"c2 :";
    oc2.display();
    cout<<endl;   
    return 0;
}

No comments:

Post a Comment