Tuesday, October 2, 2012

program to illustrate pass by reference method


#include<iostream.h>
#include<conio.h>
class sample
{
int x;
public:
void read()
{
cout<<"Enter the value\n";
cin>>x;
}
void display()
{
cout<<"The sum is\n";
cout<<x;
}
void add(sample &s1,sample &s2)
{
x=s1.x+s2.x;
}
};
void main()
{
sample s1,s2,s3;
clrscr();
s1.read();
s2.read();
s3.add(s1,s2);
s3.display();
getch();
}

Pass by value

When you use pass-by-value, the compiler copies the value of an argument in a calling function to a corresponding non-pointer or non-reference parameter in the called function definition. The parameter in the called function is initialized with the value of the passed argument. As long as the parameter has not been declared as constant, the value of the parameter can be changed, but the changes are only performed within the scope of the called function only; they have no effect on the value of the argument in the calling function.

Pass by reference

Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function.In C, the corresponding parameter in the called function must be declared as a pointer type. In C++, the corresponding parameter can be declared as any reference type, not just a pointer type.
In this way, the value of the argument in the calling function can be modified by the called function.

Difference between pass by value and pass by reference  

In pass by value approach, the called function creates another copies of the variables passes as arguments. In this approach, the values of the original variables remain unchanged. However, we come across situations where we need to change the values of the original variables. Then the values may b passed by reference

No comments:

Post a Comment