Swap value of data member of class using friend function

Thursday, November 05, 2015 Unknown 2 Comments


Swap two value of two classes using friend function

  • Description :
                Friend function access private data of class so we can use friend function as bridge between two classes.

#include<iostream.h>
#include<conio.h>
class B;
class A
{
        int a;
        public:
        void getA()
        {
             cout<<"enter value of A : ";
             cin>>a;
        }
        friend void swap(A &,B &);
};
class B
{
         int b;
         public:
         void getB()
         {
                 cout<<"enter value of B : ";
                 cin>>b;
         }
         friend void swap(A &,B &);
};
void swap(A &a1,B &b1)
{
          int temp;
          temp=a1.a;
          a1.a=b1.b;
          b1.b=temp;
          cout<<"A = "<<a1.a;
          cout<<"B = "<<b1.b;
}

void main()
{
         A a1;
         B b1;
         a1.getA();
         b1.getB();
         swap(&a1,b1);
         getch();
}


OUTPUT:-
enter value of A : 10
enter value of B : 20
A = 20
B = 10
To know about God and Godly University please click here : www.pbks.info

2 comments: