C++ can have three kinds of variable, leading to three kinds of assignment, passing of arguments to functions, and returning values from functions. From C it inherits value and pointer variables.
int i1; float sum_of_money; Graphic g1, g2; Telescope t1;where
int
and float
are examples of base types, and
Graphic
and Telescope
are names of classes already declared.
int* p1; float* pointer_to_sum_of_money; Graphic* pG1, pG2; Telescope* pt1;declare pointer variables of the same types.
In order to be useful, a pointer variable must be made to point to an existing object. This can be done by initialization:
int* p1 = &i1; Graphic* pG1 = &g1;or by assignment:
pG2 = &g2; pt1 = &t1;The ampersand (&) is the "address-of" operator that comes from C.
Pointers may also be initialized or assigned through the
new
operator. They can
be used in parameter lists as well as as return types.
int& ri1; Graphic& rG1; Telescope& rt1;The best way to think of reference variables is as aliases, i.e. a reference variable adds a name to an existing object. For this reason, "free" reference variables, such as the ones above are not allowed unless initialized:
int& ri1 = i1; Graphic& rG1 = g1; Telescope& rt1 = t1;Now ri1 is another name for the object i1, rG1 for object g1 and rt1 for object t1. References are however allowed as class members (as long as they are initialized by some constructor), as parameters, and as return types.
One advantage of references over pointers is a simpler syntax. Compare the two "swap" functions below:
void pswap(int* pi1, int* pi2) { int* ptemp = pi1; *ptemp = *pi1; *pi1 = *pi2; *pi2 = *ptemp; }called with:
int i1 = 12, i2 = 20; pswap(&i1, &i2); void rswap(int& ri1, int& ri2) { int temp; temp = ri1; ri1 = ri2; ri2 = temp; }called with:
int i1 = 12, i2 = 20; rswap(i1, i2);Both pswap and rswap produce the same result - the swapping of values in i1 and i2.
In theory the reference variable can replace most uses of pointers, but in practice, pointers are still used, especially with dynamic allocation.
Copyright © 2003 Roger Hartley