What would be a brief definition of a reference variable in C++?
A reference variable provides an alias (alternative name) for a previously defined variable. For example:
float total=100;
float &sum = total;
It means both total
and sum
are the same variables.
cout<< total;
cout << sum;
Both are going to give the same value, 100
. Here the &
operator is not the address operator; float &
means a reference to float.
Reference variables allow two variable names to address the same memory location:
int main()
{
int var1;
// var2 is a reference variable, holds same value as var1
int &var2 = var1;
var1 = 10;
std::cout << "var1 = " << var1 << std::endl;
std::cout << "var2 = " << var2 << std::endl;
}
Resource: LINK
A Reference variable is an alias for the variable name.
It is different from the pointers in following ways:
It's a variable which references another one:
int foo;
int& bar = foo;
bar
is now a reference, which is to say that bar
holds the location of memory where foo
lies.
See here for more information.
Page 79 ~ 80 C++ Primer 5th ed.
Object: A region of memory that has a type
Variable: Named object or reference
Reference: An alias for another object.
A reference variable and a pointer variable are the exact same thing to the machine (the compiler will generate the same machine code).
The most obvious advantages of using a reference variable over a pointer variable in my knowledge:
In the code below, the left side is using a reference variable, and the right side is using a pointer variable. They are the same thing to the machine, but you see the using reference variable saves you a little bit of typing.
Reference variable Pointer variable
int a = 1; ~~~~~~ int a = 1;
int &b = a; ~~~~~~ int *b = &a;
b = 2; ~~~~~~ *b = 2;
cout << a << '\n' ~~~~~~ cout << a << '\n'
==============================================
2 ~~~~~~ 2