Saturday, 31 March 2018

Object as Function Argument

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 comment:

Popular Posts

Categories

Android (21) AngularJS (1) Books (3) C (75) C++ (81) Data Strucures (4) Engineering (13) FPL (17) HTML&CSS (38) IS (25) Java (85) PHP (20) Python (85) R (69) Selenium Webdriver (2) Software (13) SQL (27)