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

returning by reference

Code 1

class Drink
        {
        public:
        Drink( char *name_ ) : name( name_ ) {}
        char *name;
        char  get(int i) const { return name[i]; }
       };

Code 2

class Drink
        {
        public:
        Drink( char *name_ ) : name( name_ ) {}
        char *name;
        char & get(int i) const { return name[i]; }
       };

Why the second code is better

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

The only reason I know for returning the reference is when overloading operator[] so that it can be changed by the calling function. I suppose if the object being returned is large enough one could return a reference (or pointer) instead of a copy just to save processing time. In your example, the first version is the best.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You