Program To Demonstrate Passing Of An Object(s) By Reference Using C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code


To copy code: Click View Source “View Source” on the right of this code snippet.

Background and Explanation of the code

The above program maintains account information of two accounts and transfer money from one account to another.The class acc_info contains two private data members acctno and balance and three public member functions read ( ) , show ( ) and transfer_money ( ).The statement given below transfers money from acct1 to acct2.

acct1.transfer_money ( acct2, money_trans);

It invokes a member function transfer_money ( ) of class acc_info through an object  acct1 with two arguments acct2 and money_trans.The first argument acct2 is an object which is passed by reference.Its alias acct is created in the called function instead of new copy of the passed object.So any modifications made to the reference object acct in the called function transfer_money( ) is reflected back to the original object acct2 in the calling function.If this would have been done by value then the required amount would be deducted from acct1 and added into the copy but not to the original  object acct2.

The second argument money_trans contains the money to be transferred and is passed by value so that it can be used in the called function.


Enter account information of acct 1…

Enter the account number =  101

Enter the balance =  5000

Enter account information of acct 2….

Enter the account number =  102

Enter the balance =  2000

Displaying account information before transfer…

Account number is =  101

Balance is = 5000

Account number is = 102

Balance is = 2000

Enter amount to transfer from acct1 to acct2 = 500

Displaying account information after transfer of money…

Account number is =  101

Balance is =  4500

Account number is =  102

Balance is =  2500