What does the & mean in the following?
class Something
{
public:
int m_nValue;
const int& GetValue() const { return m_nValue; }
int& G
It means return value by reference:
int& GetValue()
^ Means returns a reference of int
Like
int i = 10;
int& GetValue() {
int &j = i;
return j;
}
j
is a reference of i
, a global variable.
Note: In C++ you have three kinds of variables:
int i = 10
.int &j = i;
reference variable creates alias of other variable, both are symbolic names of same memory location.int* ptr = &i
. called pointers. Pointer variables use for holding address of a variable.Deference in declaration
Pointer:
int *ptr = &i;
^ ^ & is on the left side as an address operation
|
* For pointer variable.
Reference:
int &j = i;
^
| & on the right side for reference
Remember in C you have only two kinds of variables value and address (pointer). Reference variables are in C++, and references are simple to use like value variables and as capable as pointer variables.
Pointers are like:
j = &i;
i j
+------+ +------+
| 10 | | 200 |
+------+ +------+
202 432
Reference are like:
int &j = i;
i, j
+------+
| 10 |
+------+
No memory is allocated for j. It's an alias of the same location in memory.
What are the differences between pointer variable and reference variable in C++?
Because as you commented, you have questions about the differences between pointers and reference variables, so I highly encourage you read the related pages from the link I have given in my answer.