Return By Ref

What is the Purpose of Return By Reference .  Explain with a sample Prog.
senexpertAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.