Class Objects as Function Arguments (Parameters)

Like any other data-type, an object may be used as a function argument. This can be done in two ways:

  1. A copy of the entire object is passed to the function
  2. Only the address of the object is transferred to the function

The first method is called pass-by-value. Since a copy of the object is passed to the function, any changes made to the object inside the function do not affect he object used to call the function.

The second method is called pass-by-reference. When an address of the object is passed, the called function works directly on the actual object used in the call. This means that nay changes made to the object inside the function will reflect in the actual object. The pass-by-reference method is more efficient since it requires to pass only the address of the object and not the entire object.

Program given below illustrates the use of objects as function arguments. It performs the addition of time in the hour and minutes format.

The output of the above program would be:
T1 = 2 hours and 45 minutes
T2 = 3 hours and 30 minutes
T3 = 6 hours and 15 minutes

In the above program:

  1. Since the member function sum() is invoked by the object T3, with the objects T and T2 as arguments, it can directly access the hours and minutes variables of T3
  2. But, the members of T1 and T2 can be accessed only by using the dot operator (like T1.hours and T1.minutes). Therefore, inside the function sum(), the variables hours and minutes refer to T3. T1.hours and T1.minutes refer to T1, and T2.hours and T2.minutes refer to T2
  3. An object can also be passed as an argument to a non-member function. However, such functions can have access to the public member functions only through the objects passed as arguments to it. These non-member functions cannot have access to the private data members

You may also like...

1 Response

  1. pawan sonawane says:

    not executed that program well be change in program function

Leave a Reply

Your email address will not be published. Required fields are marked *