A reference is not a variable and not quite part of the type in the way you seem to think.
1 2
|
int foo;
int & bar = foo;
|
The foo is a variable and has type int.
The bar is an alias for foo. The foo has type int.
On your line 5 you do create an alias for
array[length-1]
. The type of
array[length-1]
is int.
You could have written the function like this too:
1 2 3 4 5
|
int& getLastElement(int * array, int length)
{
std::cout<<"Last element: "<<array[length-1]<<std::endl;
return array[length-1];
}
|
When you call the function:
1 2
|
int & ref = getLastElement(array,length);
int val = getLastElement(array,length);
|
Is effectively same as:
int & ref = array[length-1]; // alias
int val = array[length-1]; // copy[/code]
If you do remove the reference from the "function's return type", then the returned value is a copy:
int getLastElement(int * array, int length);
Almost like writing:
1 2 3
|
int tmp = array[length-1];
int & ref = tmp;
int val = tmp;
|
Almost, because there is no named variable 'tmp'; the return value of a function is an unnamed temporary variable that ceases to exist when the statement is over. One cannot create a non-const reference/alias to unnamed temporary.