Question

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;
}
Was it helpful?

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.

OTHER TIPS

By passing the values by reference, your exchange method will be able to modify the objects in memory. Try without the & and see what happens! Your exchange() method will instead take copies of the object you pass in, but not actually modify the data as it's stored in memory; in other words, the changes that occur when leaving off the & are local to that method, since the method is getting a copy and not the reference to the memory location of that object!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top