Reference-type in Functions

Pass by reference

  • Allows modifications of the actual parameters:

     1// modifies the actual parameter
     2// no return value
     3void addOne(int &var) {
     4  ++var;
     5}
     6
     7int main() {
     8  int a = 10;
     9  addOne(a);  // the actual parameter is a, must be an lvalue
    10  cout << a << endl;  // 11
    11  return 0;
    12}
    
  • Avoid duplication of the value (reduce overhead when the value is an object):

     1string processText(const string &inputText) {
     2  string processedText;
     3  // process the text
     4  return processedText;
     5}
     6
     7int main() {
     8  string inputText = "This is a very long text";
     9  string result = processText(inputText);
    10  cout << result << endl;
    11}
    
  • It is a good practice to always use pass-by-reference for objects (class-typed variables)

  • Extensively used in many scenarios

    • copy constructor

    • copy assignment operator overloading

Returning a Reference

Returning a reference allows a function call to be used as a lvalue. It allows modifications to the result of a function call.

 1class MyArr {
 2 private:
 3  int *arr;
 4  int size;
 5 public:
 6  MyArr();
 7  MyArr(int size, int value);
 8  ~MyArr();
 9  int &at(int i);
10};
11
12// returns a reference
13int & MyArr::at(int i) {
14  return arr[i];  // the reference to arr[i] is passed out
15}
16
17int main() {
18  MyArr myArr1(10, 10);
19  myArr1.at(0) = 10;  // you can assign a value to a function call now
20                      // because myArr1.at() is an alias of myArr1.arr[i]
21  myArr1.at(1)++;
22}

Warning

Never return a reference to a local variable! Returning a reference to an instance variable is fine.