Concepts of Programming Languages

(Sean Pound) #1

296 Chapter 6 Data Types


variable in its definition, and after initialization a reference type variable can
never be set to reference any other variable. The implicit dereference prevents
assignment to the address value of a reference variable.
Reference type variables are specified in definitions by preceding their
names with ampersands (&). For example,

int result = 0;
int &ref_result = result;

...
ref_result = 100;


In this code segment, result and ref_result are aliases.
When used as formal parameters in function definitions, C++ reference
types provide for two-way communication between the caller function and
the called function. This is not possible with nonpointer primitive param-
eter types, because C++ parameters are passed by value. Passing a pointer
as a parameter accomplishes the same two-way communication, but pointer
formal parameters require explicit dereferencing, making the code less read-
able and less safe. Reference parameters are referenced in the called func-
tion exactly as are other parameters. The calling function need not specify
that a parameter whose corresponding formal parameter is a reference type
is anything unusual. The compiler passes addresses, rather than values, to
reference parameters.
In their quest for increased safety over C++, the designers of Java removed
C++-style pointers altogether. Unlike C++ reference variables, Java reference
variables can be assigned to refer to different class instances; they are not con-
stants. All Java class instances are referenced by reference variables. That is,
in fact, the only use of reference variables in Java. These issues are further
discussed in Chapter 12.
In the following, String is a standard Java class:

String str1;

...
str1 = "This is a Java literal string";


In this code, str1 is defined to be a reference to a String class instance or
object. It is initially set to null. The subsequent assignment sets str1 to refer-
ence the String object, "This is a Java literal string".
Because Java class instances are implicitly deallocated (there is no explicit
deallocation operator), there cannot be dangling references in Java.
C# includes both the references of Java and the pointers of C++. However, the
use of pointers is strongly discouraged. In fact, any subprogram that uses pointers
must include the unsafe modifier. Note that although objects pointed to by refer-
ences are implicitly deallocated, that is not true for objects pointed to by pointers.
Pointers were included in C# primarily to allow C# programs to interoperate with
C and C++ code.
Free download pdf