• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 169
  • Last Modified:

Return By Ref

What is the Purpose of Return By Reference .  Explain with a sample Prog.
0
senexpert
Asked:
senexpert
  • 3
1 Solution
 
jasonclarkeCommented:
return by reference can be useful, as long as you take care in the use of it.  Among other things it allow class methods to act as lvalues, that is values that can be assigned to.  A good use would be in the design of a simple array class in overloading the [] operator:

class SimpleArray {
public:
    SimpeArray(size_t size);
    int& operator[](size_t index)
    { return array[index]; }
private:
    int* array;
};

//..

SimpleArray sa(20);
for (size_t i=0; i<20; i++)
{
   sa[i] = 0;   // Calls operator []
}

Obviously this only illustrates how you might use return by reference etc.  Obviously you would have to fill in the gaps, provide error checking etc.
0
 
jasonclarkeCommented:
BTW, I didn't expand on what I meant by take care.  You have to be careful not to leave dangling references around, i.e. given the above, the following situation could lead to disaster:

SimpleArray* sa = new SimpleArray(20);
int& val = (*sa)[5];
delete sa;
val = 23;  // disaster...

There are lots of ways to misuse return by reference.
0
 
nietodCommented:
I think this is an ansignment too.

But in either case, you've answered it jason, you might as well claim the points.
0
 
jasonclarkeCommented:
I think its probably an assignment too, but I didn't catch on until I read the other question.
0
 
danelroismanCommented:
I hope it's an answer to you question:

http://www.cleptoscastle.com/users/gibdonmoon/cpp/refvars.html

Enjoy!
Daniel
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now