Difference is only in calling the function and accessing the arguments
In function FunctionX,
1 2 3 4 5 6 7 8 9
void FunctionX (int* X1)
{
cout << *X1; // You do this to use X1.
}
// You call the function in this way
int X=50;
FunctionX(&X);
But,
In function FunctionY,
1 2 3 4 5 6 7 8 9
void FunctionY (int& X1)
{
cout << X1; // You do this to use X1. Note the absence of *
}
// You call the function in this way
int X=50;
FunctionY(X); //And here too, & is missing
The former function make use of POINTERS while the later makes use of REFERENCES. References are easy to use but some prefer pointers. But internally, they both are implemented in the same way, only syntax is different
Pointers can be null. References can't so if you want to be able to pass a null pointer you should pass a pointer. Otherwise I think references is to prefer in most cases
-Requires the address of the variable to be explicitly passed to it with the unary address-of operator.
-Requires de-referencing before reading/writing to the pointed-to variable.
-Usually 4 bytes in length.
Reference Variation:
-Doesn't require the address to be explicitly passed to it.
-Doesn't require de-referencing.
-Always points to an object, be it short-term or long-term.
-The size of a reference matches the size of the type it refers to.
-The size of a reference matches the size of the type it refers to
Does this mean that if the type is, say, a vector of n instances of a complex structure m bytes each, then the size of this references is n times m?
I wouldn't say that.
Another thing to note is that both allow the function to change the value of the variable passed to the function. If it will not be changed intentionally, it should be declared const.
Passing by reference must surely be smaller than passing a large object by value, else why bother with passing by const reference which is a very common thing.
I suspect the amount of data that needs to be copied when passing by reference is the same size as a pointer - i.e. its really a pointer under the hood.
The main advantage of references is syntax:
If you pass by reference you can use the . notation rather than the more cumbersome ->. This also means you can change to pass by value, if you need to, without having to go in and alter the code.
references also allow other things such defining the assignment operator
foo& foo::operator=(const foo&)
,
allowing functions to appear on the left hand side of =
element& container::operator[](int i)
and also method chaining such as the named parameter idiom etc.