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.

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.

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;
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.