A function is a group of statements which are used to perform a particular task. In the functions, we can pass parameters as per the need to perform the task. A parameter can be any type of a variable or even we can use an object of a class. When an object of a class is passed to a member function of the same class, it's data members can be accessed inside the function using the object name and dot operator. It can be done either by value or by reference.
Pass by value method :
When an object is passed by value means a copy of the actual object is created inside the function. This exact copy will be destroyed when the function scope is completed. Which means any changes that are made to the copy of the object inside the function will not reflect in the actual object.
Example for pass by value method :
#include
class weights
{
int kilograms;
int grams;
public:
void getdata ();
void putdata ();
void sum_weights (weights,weights) ;
} ;
void weights :: getdata()
{
cout<<"/nKilograms:";
cin>>kilograms;
cout<<"Grams:";
cin>>grams;
}
void weights :: putdata ()
{
cout<}
void weights :: sum_weights(weights wl,weights w2)
{
grams = wl.grams + w2.grams;
kilograms=grams/1000;
grams=grams%1000;
kilograms+=wl.kilograms+w2.kilograms;
}
int main ()
{
weights wl,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
wl.getdata();
cout<<" \n Enter weight #2" ;
w2.getdata();
w3.sum_weights(wl,w2);
cout<<"/n Weight #1 = ";
wl.putdata();
cout<<"Weight #2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();
return 0;
}
Output of above code:
Enter weight in kilograms and grams
Enter weight #1
Kilograms: 12
Grams: 560
Enter weight #2
Kilograms: 24
Grams: 850
Weight #1 = 12 Kgs. and 560 gms.
Weight #2 = 24 Kgs. and 850 gms.
Total Weight = 37 Kgs. and 410 gms.
Pass by reference method:
When an object is passed by reference means the address or reference of the actual object is passed to the function. Thus whatever changes are made inside the function will affect the actual object.
Example for pass by reference:
#include
void swapnumbs(int &i, int &j) {
int temp = i;
i = j;
j = temp;
}
int main(void) {
int a = 10;
int b = 20;
swapnumbs(a, b);
printf("A is %d and B is %d\n", a, b);
return 0;
}
Output of the above code:
A is 20 and B is 10