Page 245 - DCAP404 _Object Oriented Programming
P. 245
Object-oriented Programming
Notes A pointer to a variable holds its memory address using which the memory area storing the data
value of the variable can be directly accessed. For instance, the following code
float value = 1700.25
float fp = &value ; // fp stores the address of value
makes a float pointer *fp point to a float variable value. The variable value can now be accessed
through fp also (using *fp)
value
1700.25 6009 fp
6009
The call by reference method is useful in situations where the values of the original variables are
to be changed using a function. The following example program explains it:
Example: Program to swap values of two variables using pass by reference method.
#include<iostream.h>
#include<conio.h> //for clrscr)
int main( )
{ clrscr( );
void swap(int &, int &); // prototype
int a = 7, b = 4;
cout<<“Original values \n”;
cout<<“a=” << a <<, “b=” << b << “\n”;
swap(a,b); //invoke the function
cout<<“swapped values \n”;
cont<<“a=” << a << “b=” << b << “\n”;
return 0;
}
\\function definition
void swap(int & x, int & y)
{ int temp;
temp = x;
x=y;
y=temp;
}
The output produced by the above program is as follows:
Original Values
a= 7, b = 4
238 LOVELY PROFESSIONAL UNIVERSITY