Object as Function Argument in C++

How to pass object as a function argument in C++ ?

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

  1. A copy of the entire object is passed to the function. (Pass by Value).
    • Since a copy of the object is passed to the function, any change made to the object inside the function do not effect the object used to call the function.
  2. Only the address of the object is transferred to the function. (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 any changes made to the object inside the functions 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.

Example 1: Pass by Value

void swap(sample1 x,sample2 y)
{
   int t;
   t=x.a;
   x.a=y.b;
   y.b=t;
}

...

swap(obj1,obj2);

Example 2: Pass by Reference:

void swap(sample1 &x, sample2 &y)
{
   int t;
   t=x.a;
   x.a=y.b;
 
   y.b=t;
}
..
..
swap(obj1,obj2);

Related posts