2016-05-04

C++ Reference Type

Compared to C, the new reference type in C++ make more efficient memory usage.

A reference of a variable/object is just like an alias name of the variable/object. Some newbies from C to C++ usually get confused because they used to think it as a pointer. So, they may ask questions like "Can I initialize a reference to NULL value?"

Well, for a reference of a integer variable. You initialise it to NULL means the original variable is assigned with 0. This seems meaningful. But how about an object? Assigning a NULL value to an object? It doesn't make sense.

To get the reference of a variable/object, use syntax "&". For example,
int x;
int& r = x;
r = 10;
Now r is a reference of x. "r = 10" is the same as "x = 10".

Call by Reference


When passing arguments to a function, in order to optimize memory usage, we can use pointer in C. But in C++, a better way could be Call by Reference. For example, if we want to swap the contents of two variables. In C, we can do:
void swap(int* x, int* y)
{
    int t;
    t = *x;
    *x = *y;
    *y = t;
}
But in C++:
void swap(int& x, int& y)
{
    int t;
    t = x;
    x = y;
    y = t;
}
It looks more clear and elegant, right?