How to return a value by reference in C++
In addition to passing values to a function by reference, C++ also has the ability to return a value by reference.
Code
Consider the code snippet below where the function returns a value by reference:
#include <iostream>using namespace std;// Global variablestring str;// Note how the function is declared. It returns the// address of a string (str).string& test(){return str;};int main(){test() = "The quick brown fox.";cout << str;return 0;}
Explanation
- The return type of the function
testisstring&. This makes it return a reference to the variablestrinstead of the variable itself. - Note how the function call is used on the left side of the assignment statement on line 16. Since the address of
stris returned, it can be assigned a value. - This stores “The quick brown fox” into the global variable
str.
Note that local variables cannot be returned from a function that is defined to return values by reference.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved