Cpp - Passing by Reference

Introduction

A pass by reference can be coded via references or pointers as function parameters.

A parameter of a reference type is an alias for an argument.

When a function is called, a reference parameter is initialized with the object supplied as an argument.

The function can directly manipulate the argument passed to it.


void test( int& a) { 
   ++a; 
} 

Based on this definition, the statement

test( var);     // For an int variable var  

increments the variable var.

Within the function, any modification on the reference a automatically accesses the supplied variable, var.

If an object is passed as an argument by reference, the object is not copied.

Instead, the address of the object is passed to the function, allowing the function to access the object with which it was called.

Demo

// Demonstrating functions with parameters of reference type. 
#include <iostream> 
#include <string> 
using namespace std; 

bool getClient( string& name, long& nr); 
void putClient( const string& name, const long& nr); 

int main() /*  ww  w .  ja v  a2s.c o m*/
{ 
     string clientName; 
     long   clientNr; 

     cout << "\nTo input and output client data \n" 
           << endl; 
     if( getClient( clientName, clientNr))           // Calls 
       putClient( clientName, clientNr); 
     else 
       cout << "Invalid input!" << endl; 

     return 0; 
} 

bool getClient( string& name, long& nr) 
{ 
     cout << "\nTo input client data!\n" 
           << " Name:   "; 
     if( !getline( cin, name))  return false; 

     cout << " Number: "; 
     if( !( cin >> nr))  return false; 

     return true; 
} 

void putClient( const string& name, const long& nr) 
{ 
     // name and nr can only be read! 

     cout << "\n Name:   ";  cout << name 
          << "\n Number: ";  cout << nr << endl; 
}

Result

Related Topic