Loading....
Coupon Accepted Successfully!

 

Objects As Function Arguments

Similar to variables, object can be passed to functions. The following are the three methods to pass argument to a function:

  1. Pass-by-value – A copy of object (actual object) is sent to function and assigned to the object of callee function (formal object). Both actual and formal copies of objects are stored at different memory locations. Hence, changes made in formal object are not reflected to actual object.
  2. Pass-by-reference – Address of object is implicitly sent to function.
  3. Pass-by-address – Address of the object is explicitly sent to function.

In pass-by-reference and pass-by-address methods, an address of actual object is passed to the function. The formal argument is reference/pointer to the actual object. Hence, changes made in the object are reflected to actual object. These two methods are useful because an address is passed to the function and duplicating of object is prevented.

The following examples illustrate both the methods of passing objects to the function as an argument.

8.22 Write a program to pass objects to the function by pass-by-value method.

 

Explanation: In the above program, the class life is declared with three member integer variables. The function getrys() reads the integers through the keyboard. The function
period() calculates the difference between the two integers entered. In the function main(), a1 is an object to the class life. The object a1 calls the function getyrs(). Immediately after this, the same object (a1) is passed to the function period(). The function period() calculates the difference between two integers (dates) using the two data members of the same class. Thus, an object can be passed to the function. To pass an object by reference, the prototype of function period() should be as follows: 

void period ( life &);


8.23 Write a program to pass objects to the function pass-by-address method.

 

Explanation: The above program is same as previous one. In this program, the object a1 is passed by address. Consider the following statements.
 

a) void period ( life*);

b) a1.period (&a1);

a) Yr=y1->expyr-y1->mfgyr;


The statement (a) is the prototype of the function period(). In this statement, the deference operator (*) indicates that the function will accept address of the actual argument. The statement (b) is used to pass the address of the argument to the function period(). The statement (c) is used to access the member variables of the class. When an object is a pointer to the class members, then its elements are accessed by using arrow (->) operator. In this case, use of a dot operator (.) is invalid.





Test Your Skills Now!
Take a Quiz now
Reviewer Name