C++ Return by Reference

In C++ Programming, not only can you pass values by reference to a function but you can also return a value by reference.

To understand this feature, you should have the knowledge of:


Example: Return by Reference

#include <iostream>
using namespace std;

// global variable
int num;

// function declaration
int& test();

int main() {

  // assign 5 to num variable
  // equivalent to num = 5;
  test() = 5;

  cout << num;

  return 0;
}

// function definition
// returns the num variable by reference
int& test() {
  return num;
}

Output

5

In the program above, the return type of function test() is int&. Hence, this function returns a reference of the variable num.

The return statement is return num;. Unlike return by value, this statement doesn't return value of num, instead it returns the reference to the variable itself.

So, when the variable is returned, it can be assigned a value as done in test() = 5;

This stores 5 to the variable num, which is displayed onto the screen.


Important Things to Remember When Returning by Reference

  • We can't return literals from the function that should return lvalue references, since literals can't have lvalue references.
int& test() {
    // incorrect
    return 2; //returns literal
}
  • The object being returned by the function should exist even after the function returns. The local variables are destroyed once the function returns, so we should not return a local variable from the function.
// can't do
int& test() {
    int n = 2; 
    return n; // returns local variable
}

// can do
int& test() {
    static int n = 2;
    return n; // return static variable by reference
}

Also Read:

Did you find this article helpful?