An object can be used as a function argument.This can be done in two ways
1. Pass by value
2. Pass by reference
Pass by value :
In pass by value, a copy of entire object is passed to the function so any change made to the object inside the function do not affect the object used to call the function.
Pass by reference :
In pass by reference , only the object's address is transferred to the function. When an address of the object is passed, the called function works directly on the actual object used in the call.
So any change made to the object inside the function will affect in actual object.
Write a program to illustrate the use of objects as an function argument
#include<iostream.h>
#include<conio.h>
class time
{
int hours;
int minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void puttime( )
{
cout<<hours<<"Hours And"<<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;
}
void main( )
{
time t1,t2,t3;
clrscr( );
t1.gettime(2,45);
t2.gettime(3,30);
t3.sum(t1,t2);
cout<<"\n\tT1::";
t1.puttime( );
cout<<"\n\tT2::";
t2.puttime( );
cout<<"\n\tT3::";
t3.puttime( );
getch( );
}
Output :-
T1::2 Hours And 45 Minutes
T2::3 Hours And 30 Minutes
T3::6 Hours And 15 Minutes
1. Pass by value
2. Pass by reference
Pass by value :
In pass by value, a copy of entire object is passed to the function so any change made to the object inside the function do not affect the object used to call the function.
Pass by reference :
In pass by reference , only the object's address is transferred to the function. When an address of the object is passed, the called function works directly on the actual object used in the call.
So any change made to the object inside the function will affect in actual object.
Write a program to illustrate the use of objects as an function argument
#include<iostream.h>
#include<conio.h>
class time
{
int hours;
int minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void puttime( )
{
cout<<hours<<"Hours And"<<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;
}
void main( )
{
time t1,t2,t3;
clrscr( );
t1.gettime(2,45);
t2.gettime(3,30);
t3.sum(t1,t2);
cout<<"\n\tT1::";
t1.puttime( );
cout<<"\n\tT2::";
t2.puttime( );
cout<<"\n\tT3::";
t3.puttime( );
getch( );
}
Output :-
T1::2 Hours And 45 Minutes
T2::3 Hours And 30 Minutes
T3::6 Hours And 15 Minutes
0 Comments:
Post a Comment