a few questions with this code. I would appreciate some help. ostream & operator << (ostream &out, const Rational rat) { out << rat.num; return out; } 1) what does the first & between ostream and operator do. First time I ever see it. 2) why am I returning out, when it is like cout from main and why is there an ampersand on out in the argument, is it necessary? because rat doesn't have one. 4) to overload operator+ for example, it acts as a member function and is explicity called. How does this on
If I remember well this is a function and as you know in functions there are two kind of passing values : Passing by value and passing by address . So in the passage by address we use the sign &, what we mean by passage by address, it means give to that function the address of this variable and let it do some treatment then change (store the result) directly the value of this variable in the MEMORY (we gave the function the & which means memory address). Passing by value : give to this function a COPY of the variable it do some treatment and it change the value of the COPY not the value of the real variable. 2- The type of the function is : ostream, that means this function will do a specific work then it will return a result in the type "ostream", and you are returning "out", so "out" must have the type "ostream", and we use & because the function is taking the address of out to modify there. We haven't & on rat, just because the programmer doesn't need that. Good luck.
why do we not write in this way as out is passing by value and if i t is modifying,it will modify at where we call the function??? void operator << (ostream &out, const Rational rat) { out << rat.num; return out; }
No you can't write "Void" because in C/C++ we have two kind of function, one return a result and the other no, the one that return a result we must specify before the name of the function the type, as in this example "ostream", and the other which doesn't return a result, you can called it Procedure, we found before the name this word 'void'.
thnx
You're Welcome
Join our real-time social learning platform and learn together with your friends!