Search code examples
c++operator-keywordfriend-function

How to use a common friend function to exchange the private values of two classes


I copy this program in my book.But i not understand one line in this program.This line is

friend void exchange(class_1 &,class_2 &);

My question is why use & operator in bracket? Please explain.

#include <iostream>

using namespace std;


class class_2;

class class_1{
    int valuel;

    public:
    void indata(int a){valuel=a;}
    void display (void){cout<<valuel<<"\n";}
    friend void exchange (class_1&, class_2&);
};

class class_2{
    int valuel_2;
    public:

    void indata(int a){valuel_2=a;}
    void display (void){cout<<valuel_2<<"\n";}
    friend void exchange (class_1&, class_2&);
};

void exchange (class_1 &x,class_2 &y){
    int temp=x.valuel;
    x.valuel=y.valuel_2;
    y.valuel_2=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;
}

Solution

  • "&" means that the two arguments are references. See What are the differences between a pointer variable and a reference variable in C++? for more info.