Passing by reference
- Doesn't require the address-of (&) operator when passing a variable
- Doesn't require the dereference (*) operator when changing the value of a reference
- Guarantees the argument will be an object (you can't have a NULL reference)
- Guarantees the reference will always refer to the same object
Pointers are mainly used for memory management, but here's an example to contrast pointers and references:
Code:
void f (int& ref)
{
ref++; // Pretty
}
void f (int* ptr)
{
(*ptr)++; // Ugly
}
int main()
{
int var = 3;
f (var); // Pass by reference, implicit
f (&var); // Pass by pointer, explicit
f (NULL); // Oops! Pass by pointer
return 0;
}
EDIT: Posted a little too late