954,487 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Exact meaning of functions returning reference

How are functions returning reference used?? Do they return values on the left side or the right side of the assignment. I would be glad if I could get some help.
Thanks,
comwizz.

comwizz
Light Poster
39 posts since Nov 2005
Reputation Points: 10
Solved Threads: 0
 
How are functions returning reference used?? Do they return values on the left side or the right side of the assignment. I would be glad if I could get some help. Thanks, comwizz.


Try looking at this and post further queries http://www.parashift.com/c++-faq-lite/references.html#faq-8.2

SpS
Posting Pro
599 posts since Aug 2005
Reputation Points: 70
Solved Threads: 32
 

Why should references be used at all?? As we could always use pointers in place of them as if we change the value of the pointer , automatically the value of variable it points to is changed eg. p=&s;*p=7;changes the value of s also. Also , would a function returning a reference be used on the right side of assignment operator ?? eg. c=max();where max returns a reference variable having similar datatype to c.Please reply.
Thanks,
comwizz.

comwizz
Light Poster
39 posts since Nov 2005
Reputation Points: 10
Solved Threads: 0
 

one place a reference is needed and pointers will not work is overloading the [] operator. You couldn't implement this as neatly using pointers.

And the reference can be used on both left and right side of the operators, as illustrated in main() below.

#include <iostream>
using namespace std;

class matrix
{
private:
	int array[10];
public:
	matrix() {memset(array,0,sizeof(array));}
	int& operator[](int index) {return array[index];} 

};

int main()
{

	matrix m;
	m[0] = 1;
	m[1] = 2;
             int x = m[2];
	cout << m[0] << endl;
	cout << m[1] << endl;

	return 0;
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 
Why should references be used at all?? As we could always use pointers in place of them as if we change the value of the pointer , automatically the value of variable it points to is changed eg. p=&s;*p=7;

I think you almost answered your own question - why use references? Well, because pointer syntax can look ugly. pointers are also error prone. In general, use References whereever you can, only use Pointers when you have to.

Bench
Posting Pro
577 posts since Feb 2006
Reputation Points: 307
Solved Threads: 63
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You