Saturday, April 11, 2015

C++ Reference


A reference is an alias for another variable.  It is declared using the & operator

int a = 100;
int& b = a

A reference must be initialized when it is declare or results in compilation error.

Reference can be used in place of the variable (as it is just like have another name for the same variable)

a += 1 or b +=1 yields the same result

To pass by reference in a function fn is efficient if the parameter size is large

int fn(int& x, int& y)
int i, j, k

i = fn(j, k)

fn can change the value of j and k in its code.  To prevent fn changing the arguments, declare the funciton using constant reference

int fn(const int& x, const int& y)

When a function returns a reference (e.g. int& fn(...)), it must make sure that the deference is not on a local variable as the memory storage will disappear when the fn goes out of scope.  It must return either a static variable or a reference to a parameter.  The calling program can assign the return reference value to another reference variable.  In this case, the return object is not copied

int& a = fn(...)  // no copy of content

If the calling program uses a variable to receive the return value, the content of the object will be copied

int a = fn (..) // content copy

No comments: