Page 58 - DCAP404 _Object Oriented Programming
P. 58
Unit 2: Beginning of OOP Language
The first set of declarations causes m to refer to x which is pointed to by the pointer p and the Notes
statement in (2) creates an int object with value 50 and name n.
A major application of reference variables is when passing arguments to functions. Consider the
following code snippet:
void f(int &x) // uses reference
{
x = x+10; // x is incremented; so also m
}
main ( )
{
int m = 10;
f(m); // function call
….
…
}
When the function call f(m) is executed, the following initialization occurs:
Int &x = m;
Thus x becomes an alias of m after executing the statement f(m);.
Since the variable x and m are aliases, when the function increments x, m is also incremented.
The value of m becomes 20 after the function is executed. In traditional C, we accomplish this
operation using pointers and dereferencing techniques.
The call by reference mechanism is useful in object-oriented programming because it permits
the manipulation of objects by reference and eliminates the copying of object parameters back
and forth.
Notes Note that the references can be created not only for built-in data types but also for
user-defined data types such as structures and classes. References work wonderfully well
with these user-defined data types.
Self Assessment
Fill in the blanks:
13. The scope of a variable extends from the point of its declaration till the end of
the……………….., containing the declaration.
14. (.) operator does not work on ………………….. or reference type variables.
15. A reference variable provides an alias (alternative name) for a previously
defined………………... .
LOVELY PROFESSIONAL UNIVERSITY 51