Objects as Function Arguments in C++ Programming | C++ Programming

Objects as Function Arguments

Like any other data type, an object may be used as a function argument in three ways: pass-by-value, pass-by-reference, and pass-by-pointer.



Pass-by-value:

In this method, 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 in the function call. For example,
distance adddistance(distance d) 
{ 
distance dd; 
dd.feet = feet + d.feet; 
dd.inches = inches + d.inches; 
dd.feet=dd.feet +dd.inches/12 
dd.inches=dd.inches%12;
return dd;
}


Pass-by-reference:

In this method, an address of the object is passed to the function. The function works directly on the actual object used in the function call. This means that any changes made to the object inside the function will reflect in the actual object. For example,
distance adddistance(distance& d2) 
{ 
distance d3; 
d3.feet = feet + d2.feet; 
d3.inches = inches + d2.inches; 
d3.feet=dd.feet +dd.inches/12 
d3.inches=dd.inches%12;
return d3;
}


Pass-by-pointer:

Like pass-by-reference method, pass-by-pointer method can also be used to work directly on the actual object used in the function call. For example,
distance adddistance(distance* d2) 
{ 
distance d3;  d3.feet = feet + d2->feet; 
d3.inches = inches + d2->inches; 
d3.feet=dd.feet +dd.inches/12 
d3.inches=dd.inches%12;
return d3;
}
This function must be called as follows:
d3 = d1.adddistance(&d2);

Comments

Popular posts from this blog

C Program for SCAN Disk Scheduling Algorithm | C Programming

C program to Find Cartesian Product of Two Sets | C programming

C Program To Check The String Is Valid Identifier Or Not | C Programming