An object may be used as function arguments in two methods:-
i) A copy of the entire object is passed to the function.
ii) Only the address of the object is transferred to the function.
1) 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 the object used to call the function.
2) 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 function will reflect in the actual object.
Example:
Following program illustrates the use of object as function arguments.
It performs the addition of time in the hour & minute format.
# include<iostream.h>
class time
{
int hours;
int minutes;
public:
void gettime(int h, int m)
{
hours = h;
minutes = m;
}
void puttime(void)
{
cout<< hours << "hours and: ";
cout<< minutes << " minutes " << "\n";
}
void sum (time, time);
};
void time :: sum (time t1, time t2)
{
minutes =t1.minutes + t2.minutes ;
hours = minutes / 60;
minutes = minutes%60;
hours = hours = t1.hours + t2.hours;
}
main()
{
time T1, T2, T3;
T1.gettime(2, 30);
T2.gettime(3, 45);
T3.sum(T1, T2);
cout<< " T1 = ";
T1.puttime();
cout<< " T2 = ";
T2.puttime();
cout<< " T3= ";
T3.puttime();
}
An object can also be passed as argument to a non-member function but, such functions can have access to the public member function only through the object passed as arguments to it.