Class Objects as Function Input and Output


Class Objects as Arguments of Functions

The examples so far have only provided for input into the methods of non-class arguments. However, it is possible to have class objects as arguments of any method as well as non-class objects. For example in the function total_of_account(), the bank_account class objects c and s are used as arguments. See example banktotl.cpp.

image from book

 void totalOfAccount(BankAccount c,BankAccount s) {    amount = c.amount + s.amount; } 

image from book

This method is then called by the BankAccount class object bothAccounts as follows:

image from book

 bothAccounts.totalOfAccount(checkingAccount, savingsAccount); 

image from book

There is no output from this method. The method acts on bothAccounts internally by modifying the calling object's data members.

Class Objects as Output of Functions

It is possible to have class objects as arguments and it is also possible to have class objects as method output. For example, the following class method has both a bank_account class object s as an argument and a bank_account object as output. See example bankttl2.cpp.

image from book

 BankAccount plus(BankAccount s) (   BankAccount temp;   temp.amount = amount + s.amount;   return temp; } 

image from book

The implementation of this method may confuse you unless you remember that this method must be called by a BankAccount object as in the following:

image from book

 bothBccounts = checkingAccount.plus(savingsAccount); 

image from book

Passing Objects and Arrays of Objects to Functions

Both of the examples above have objects as input to class methods, but it is also possible to have class objects as both input and output of non-method functions. See example: invoice2.cpp.

When an object is an argument to a function, it may be passed by value or by reference. If the object is very large, it may be better to use pass by reference to reduce the amount of time and the amount of member needed when passing the object. The previous example passed an object by value. See example: invoice3.cpp for an example of passing an object of a class by reference.

Not only can a single object be passed into a function, but it is also possible for an array of objects to be an argument of a function. As you recall, arrays are passed by reference. See examples invoice4.cpp for an example which passes arrays of objects.




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net