This example might help you see what int & would be returning.
Code:
int& func(int &a)
{
return a;
}
int main()
{
int *a = new int(1);
int *t;
t = &(func(*a));
*a = 10;
cout<<"Value of t: "<<*t<<endl
<<"Value of a: "<<*a<<endl;
delete a;
return 0;
}
The output is
Code:
Value of t: 10
Value of a: 10
The behavior of references made more sense to me once I started messing around with pointers. Since "a" and "t" are both integer pointers, what effectively happened is func() made the pointer "t" point to the same memory that "a" is pointing to.
If "a" and "t" are NOT pointers, the code will be modified like this
Code:
#include<iostream>
using namespace std;
int& func(int &a)
{
return a;
}
int main()
{
int a = 1;
int t;
t = func(a);
a = 10;
cout<<"Value of t: "<<t<<endl
<<"Value of a: "<<a<<endl;
return 0;
}
And the output will be
Code:
Value of t: 1
Value of a: 10
In this case, IMO, it's pointless to have function return by reference. However, if you are working on embedded software, writing a kernel, or device driver the memory saving might be worth the strange looking function.
HTH