View Single Post
Old 01-28-2005, 08:57 PM   #16 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,546
Valmont is on a distinguished road
fp_unit:
We return by reference to prevent the creation of temporaries. Temporaries get lost once we get out of the function or out of scope. See this page for details on it. This is the answer to the return-by-reference question on operator=().

Page 3:

*** Chapter One ***

Returning by reference. A recap.

There is no way one can decently understand and implement operator overloading without understanding the basics of a function that returns a reference. Observe the little code below. It will be followed by a short remark only. Refer to your study book if this topic is completely new to you.
- Step(1) int& SomeFunction enables SomeFunction to be used as a lefthandside value. Observe the placement of the ampersand (&)!
Code:
#include <iostream>
 
using namespace std;
int& SomeFunction(int& a, int& b, int& c)
{
  // Step(2) Variable "c" can change the variable it points to. return c;
}

int main()
{
  int MyInt_1 =7, MyInt_2=8, MyInt_3=9;
  
  /* Step(3)
  * The assignment below basically means: MyInt3 = 230;
  * Why? Because "c" is returned by SomeFunction, AND 
  * MyInt_3 is passed to "int& c", AND
  * there is an ampersand (&) in "int& SomeFunction". 
  */ //Somefunction is lhs because of "int&" as return type!  
  SomeFunction(MyInt_1, MyInt_2, MyInt_3)=230;
  cout<<MyInt_1<<endl;  
  cout<<MyInt_2<<endl;  
  cout<<MyInt_3<<endl;
  
  return 0;
}
The output for MyInt_3 is 230! Not 9.
So how do you change MyInt_2? Why easy. Just return b instead of c in SomeFunction(int& a, int& b, int& c).
That's it. Now we move to our first example of operator overloading.
__________________
Valmont is offline   Reply With Quote