Creating a reference variable in two statements - c++

int x;
int& foo = x;
// foo is now a reference to x so this sets x to 56
foo = 56;
How can I split the statement int& foo = x; into two statements?
By splitting, I mean using two statements such as in the below example:
int y;
int* ptr = &y;
I can split the int* ptr = &y into two statements declaring the pointer first.
int* ptr;
ptr = &y; //then assigning the pointer to point to y
How to do a similar thing to a reference? I'm looking also for an explanation on why or why not?

No, this can not be done, there are only a few cases where an intializer for a reference can be omitted, from the draft C++ standard section 8.5.3 [dcl.init.ref]:
The initializer can be omitted for a reference only in a parameter
declaration (8.3.5), in the declaration of a function return type, in
the declaration of a class member within its class definition (9.2),
and where the extern specifier is explicitly used. [ Example:
int& r1; // error: initializer missing
extern int& r2; // OK
—end example ]
As to why we find the following rationale for why references are not resettable from The Design and Evolution of C++:
It is not possible to change what a reference refers to after
initialization. That is once a C++ reference is initialized it cannot
be made to refer to a different object later; it cannot be re-bound. I
had in the past been bitten by Algol68 references where r1=r2 can
either assign through r1 to the object referred to or assign to a new
reference value to r1 (re-binding r1) depending on the type of r2. I
wanted to avoid such problems in C++.

You just can't. Consider the reference like a const pointer:
int& foo = x is the same as int * const foo = &x.
That's why you can't re-assign a reference, or declare a new one without a value.

No you can't.
A possible workaround is to use std::boost::optional<T&> or simply T*
int x;
boost::optional<int&> foo; // or int* foo = nullptr;
foo = x; // foo = &x;
// foo is now a 'reference' to x
*foo = 56; // now, we have x == 56

There is such a thing as an empty pointer, but there is not such a thing as an empty reference. A reference has to have something that it refers to. It must be initialized.
int& r; // error
This is one of the main differences between a pointer and a reference, and is one of the reasons to potentially prefer taking a reference argument (must be valid) over a pointer argument (can be null).

You have no way to do this.
Reference should be constant so you may only initialize it.

No, a reference must be initialised as it is declared to support the guarantee that there are no references that point into nowhere.

Related

what is the difference between int &val2 = val and int val3 = val? [duplicate]

What would be a brief definition of a reference variable in C++?
A reference is an entity that is an alias for another object.
A reference is not a variable as a variable is only introduced by the declaration of an object. An object is a region of storage and, in C++, references do not (necessarily) take up any storage.
As objects and references are distinct groups of entities in C++ so the term "reference variable" isn't meaningful.
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.
A reference variable is an alias (an alternate name) for an object. [From the C++ FAQ].
The first paragraph of the Wikipedia article could easily serve as a brief definition:
In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C.
And quoting from the same article:
C++ references differ from pointers in several essential ways:
It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.
Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.
References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor.
Further reading:
Wikipedia: Reference C++
Cprogramming.com: C++ References
Stack Overflow: Difference between pointer variable and reference variable in C++
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.
A Reference variable is an alias for the variable name.
It is different from the pointers in following ways:
You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.
Once a reference is initialized to an object, it cannot be changed to point to any another object whereas in case of pointer we can make it point to any other object at any time.
A reference must be initialized the time it is created. Pointers can be made initialized at any time.
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 is an alternative label, an alias, for the object it is initialized with. Once a reference is initialized it can not be changed to be an alternative label or alias of some other object. After the initialization the reference or the object variable may be used interchangeably.
A reference has some of the characteristics of a const pointer to an object in that it is initialized when defined. And while what it references or points to can be changed, the reference or the const pointer itself can not be changed. However since a reference is an alternative label or alias it may or may not actually exist as a data object unlike a const pointer which will probably exist unless the compiler can optimize it away. And even if a reference is created as an actual entity by the compiler, that is compiler housekeeping and should be ignored since it officially does not exist much like the man behind the curtain in the Emerald City.
The following code samples gives examples comparing and contrasting reference with pointer and const pointer:
int myInt; // create a variable of type int, value not initialized
int myInt2 = 3; // create a second variable of type int with a value of 3
int &rInt = myInt; // create a reference to the variable of type int, myInt
rInt = 5; // myInt now has a value of 5, the reference is an alias for myInt
rInt++; // myInt now has a value of 6, the reference is an alias for myInt
rInt = myInt2; // myInt now has the same value as myInt2, a value of 3
int *pInt = &rInt; // pInt points to myInt
(*pInt)++; // increments myInt
pInt++; // increments the pointer which formerly pointed to myInt
int &rInt2; // error C2530: 'rInt2' : references must be initialized
int *pInt2; // just fine, uninitialized pointer is ok
int * const pInt3; // error C2734: 'pInt3' : const object must be initialized if not extern
int * const pInt4 = &myInt; // define and initialize const pointer
pInt4 = &myInt2; // error C3892: 'pInt4' : you cannot assign to a variable that is const
There are actually two kinds of references: an lvalue reference and an rvalue reference.
An lvalue reference is the same reference in the C++ language before C++11. An rvalue reference was introduced in C++11 to allow for a reference to a temporary object to assist with doing a move rather than a copy and some other actions where a copy is the wrong approach but a move is the right approach.
For example a comparison of lvalue reference and rvalue reference in the following simple source lines. Because these are int references that means that an assignment of a non-integer value results in the compiler doing a conversion which results in a temporary variable. An rvalue reference can bind to a temporary variable and an lvalue reference can not.
// assign a double to an int causing creation of temporary
int &rIntd1 = 1.2; // error C2440: 'initializing' : cannot convert from 'double' to 'int &'
int &&rIntd2 = 1.2; // warning C4244: 'initializing' : conversion from 'double' to 'int', possible loss of data
rInt = rIntd2; // myInt from the code above now has a value of 1, 1.2 was truncated when converting from double to int
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:
Easy to understand (no address, de-reference all kinds of headache things)
Saves you a tiny bit of typing, adn thus probably less error-prone.
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
Reference variables (let a), just say for easy understanding, another name of variable (let x), which holds the same exact memory location as that of x.
int &a = x; refers that a holds same memory location as that of x.
For example, say two roommates share the same room. One friends name is x and another friends name is a. If a changes the location of the table placed in the room, from position (x,y,z) to (x1,y1,z1) then changes are visible to friend x as well and vice versa.
A reference is an alternative name for an object. A reference variable provides an alias for previously defined variables. A reference declaration consists of a base type an & a reference variable equated to a variable name.
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.

What is the difference between MyClass and MyClass& in C++? [duplicate]

What would be a brief definition of a reference variable in C++?
A reference is an entity that is an alias for another object.
A reference is not a variable as a variable is only introduced by the declaration of an object. An object is a region of storage and, in C++, references do not (necessarily) take up any storage.
As objects and references are distinct groups of entities in C++ so the term "reference variable" isn't meaningful.
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.
A reference variable is an alias (an alternate name) for an object. [From the C++ FAQ].
The first paragraph of the Wikipedia article could easily serve as a brief definition:
In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C.
And quoting from the same article:
C++ references differ from pointers in several essential ways:
It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.
Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.
References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor.
Further reading:
Wikipedia: Reference C++
Cprogramming.com: C++ References
Stack Overflow: Difference between pointer variable and reference variable in C++
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.
A Reference variable is an alias for the variable name.
It is different from the pointers in following ways:
You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.
Once a reference is initialized to an object, it cannot be changed to point to any another object whereas in case of pointer we can make it point to any other object at any time.
A reference must be initialized the time it is created. Pointers can be made initialized at any time.
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 is an alternative label, an alias, for the object it is initialized with. Once a reference is initialized it can not be changed to be an alternative label or alias of some other object. After the initialization the reference or the object variable may be used interchangeably.
A reference has some of the characteristics of a const pointer to an object in that it is initialized when defined. And while what it references or points to can be changed, the reference or the const pointer itself can not be changed. However since a reference is an alternative label or alias it may or may not actually exist as a data object unlike a const pointer which will probably exist unless the compiler can optimize it away. And even if a reference is created as an actual entity by the compiler, that is compiler housekeeping and should be ignored since it officially does not exist much like the man behind the curtain in the Emerald City.
The following code samples gives examples comparing and contrasting reference with pointer and const pointer:
int myInt; // create a variable of type int, value not initialized
int myInt2 = 3; // create a second variable of type int with a value of 3
int &rInt = myInt; // create a reference to the variable of type int, myInt
rInt = 5; // myInt now has a value of 5, the reference is an alias for myInt
rInt++; // myInt now has a value of 6, the reference is an alias for myInt
rInt = myInt2; // myInt now has the same value as myInt2, a value of 3
int *pInt = &rInt; // pInt points to myInt
(*pInt)++; // increments myInt
pInt++; // increments the pointer which formerly pointed to myInt
int &rInt2; // error C2530: 'rInt2' : references must be initialized
int *pInt2; // just fine, uninitialized pointer is ok
int * const pInt3; // error C2734: 'pInt3' : const object must be initialized if not extern
int * const pInt4 = &myInt; // define and initialize const pointer
pInt4 = &myInt2; // error C3892: 'pInt4' : you cannot assign to a variable that is const
There are actually two kinds of references: an lvalue reference and an rvalue reference.
An lvalue reference is the same reference in the C++ language before C++11. An rvalue reference was introduced in C++11 to allow for a reference to a temporary object to assist with doing a move rather than a copy and some other actions where a copy is the wrong approach but a move is the right approach.
For example a comparison of lvalue reference and rvalue reference in the following simple source lines. Because these are int references that means that an assignment of a non-integer value results in the compiler doing a conversion which results in a temporary variable. An rvalue reference can bind to a temporary variable and an lvalue reference can not.
// assign a double to an int causing creation of temporary
int &rIntd1 = 1.2; // error C2440: 'initializing' : cannot convert from 'double' to 'int &'
int &&rIntd2 = 1.2; // warning C4244: 'initializing' : conversion from 'double' to 'int', possible loss of data
rInt = rIntd2; // myInt from the code above now has a value of 1, 1.2 was truncated when converting from double to int
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:
Easy to understand (no address, de-reference all kinds of headache things)
Saves you a tiny bit of typing, adn thus probably less error-prone.
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
Reference variables (let a), just say for easy understanding, another name of variable (let x), which holds the same exact memory location as that of x.
int &a = x; refers that a holds same memory location as that of x.
For example, say two roommates share the same room. One friends name is x and another friends name is a. If a changes the location of the table placed in the room, from position (x,y,z) to (x1,y1,z1) then changes are visible to friend x as well and vice versa.
A reference is an alternative name for an object. A reference variable provides an alias for previously defined variables. A reference declaration consists of a base type an & a reference variable equated to a variable name.
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.

What is a constant reference? (not a reference to a constant)

Why do constant references not behave the same way as constant pointers, so that I can actually change the object they are pointing to? They really seem like another plain variable declaration. Why would I ever use them?
This is a short example that I run which compiles and runs with no errors:
int main (){
int i=0;
int y=1;
int&const icr=i;
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99; // Can assign another value but the value is not assigned to y...
int x=9;
icr=x;
cout<<"icr: "<<icr<<", y:"<<y<<endl;
}
The clearest answer.
Does “X& const x” make any sense?
No, it is nonsense
To find out what the above declaration means, read it right-to-left:
“x is a const reference to a X”. But that is redundant — references
are always const, in the sense that you can never reseat a reference
to make it refer to a different object. Never. With or without the
const.
In other words, “X& const x” is functionally equivalent to “X& x”.
Since you’re gaining nothing by adding the const after the &, you
shouldn’t add it: it will confuse people — the const will make some
people think that the X is const, as if you had said “const X& x”.
The statement icr=y; does not make the reference refer to y; it assigns the value of y to the variable that icr refers to, i.
References are inherently const, that is you can't change what they refer to. There are 'const references' which are really 'references to const', that is you can't change the value of the object they refer to. They are declared const int& or int const& rather than int& const though.
What is a constant reference (not a reference to a constant)
A Constant Reference is actually a Reference to a Constant.
A constant reference/ Reference to a constant is denoted by:
int const &i = j; //or Alternatively
const int &i = j;
i = 1; //Compilation Error
It basically means, you cannot modify the value of type object to which the Reference Refers.
For Example:
Trying to modify value(assign 1) of variable j through const reference, i will results in error:
assignment of read-only reference ‘i’
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99;
Doesn't change the reference, it assigns the value of the type to which the reference refers.
References cannot be made to refer any other variable than the one they are bound to at Initialization.
First statement assigns the value y to i
Second statement assigns the value 99 to i
This code is ill-formed:
int&const icr=i;
Reference: C++17 [dcl.ref]/1:
Cv-qualified references are ill-formed except when the cv-qualifiers are introduced
through the use of a typedef-name or decltype-specifier, in which case the cv-qualifiers are ignored.
This rule has been present in all standardized versions of C++. Because the code is ill-formed:
you should not use it, and
there is no associated behaviour.
The compiler should reject the program; and if it doesn't, the executable's behaviour is completely undefined.
NB: Not sure how none of the other answers mentioned this yet... nobody's got access to a compiler?
By "constant reference" I am guessing you really mean "reference to constant data". Pointers on the other hand, can be a constant pointer (the pointer itself is constant, not the data it points to), a pointer to constant data, or both.
As it mentioned in another answers, a reference is inherently const.
int &ref = obj;
Once you initialized a reference with an object, you can't unbound this reference with its object it refers to. A reference works just like an alias.
When you declare a const reference, it is nothing but a reference which refers to a const object.
const int &ref = obj;
The declarative sentences above like const and int is determining the available features of the object which will be referenced by the reference. To be more clear, I want to show you the pointer equivalent of a const reference;
const int *const ptr = &obj;
So the above line of code is equivalent to a const reference in its working way. Additionally, there is a one last point which I want to mention;
A reference must be initialized only with an object
So when you do this, you are going to get an error;
int &r = 0; // Error: a nonconst reference cannot be initialized to a literal
This rule has one exception. If the reference is declared as const, then you can initialize it with literals as well;
const int &r = 0; // a valid approach
First I think int&const icr=i; is just int& icr = i, Modifier 'const' makes no sense(It just means you cannot make the reference refer to other variable).
const int x = 10;
// int& const y = x; // Compiler error here
Second, constant reference just means you cannot change the value of variable through reference.
const int x = 10;
const int& y = x;
//y = 20; // Compiler error here
Third, Constant references can bind right-value. Compiler will create a temp variable to bind the reference.
float x = 10;
const int& y = x;
const int& z = y + 10;
cout << (long long)&x << endl; //print 348791766212
cout << (long long)&y << endl; //print 348791766276
cout << (long long)&z << endl; //print 348791766340

What is implicit dereference in C++

What exactly does implicit dereference in C++ mean? Does it mean when I pass a reference to variable into a function parameter I don't need the & in front of it to use its value?
I assume that your teacher was trying to explain the difference between pointers and references.
It is relatively common (though not technically accurate) to refer to references as fancy pointers that do implicit de-referencing.
int x = 5;
int* xP = &x;
int& xR = x;
xR = 6; // If you think of a reference as a fancy pointer
// then here there is an implicit de-reference of the pointer to get a value.
*xP = 7; // Pointers need an explicit de-reference.
The correct way to think about is not to use the "A reference is a fancy pointer". You need to think about references in their own terms. They are basically another name for an existing variable (AKA an alias).
So when you pass a variable by reference to a function. This means the function is using the variable you passed via its alias. The function has another name for an existing variable. When the function modifies the variable it modifies the original because the reference is the original variable (just another name for it).
So to answer you question:
I don't need the & in front of it to use its value?
No you don't need to add the &.
int f(int& x) // pass a value by reference
{
x =5;
}
int plop = 8;
f(plop);
// plop is now 5.
Another context in which C++ will implicitly dereference pointers is with function pointers:
void foo() { printf("foo\n"); }
void bar() {
void (*pf)() = &foo;
(*pf)(); // Explicit dereference.
pf(); // Implicit dereference.
}

What is a reference variable in C++?

What would be a brief definition of a reference variable in C++?
A reference is an entity that is an alias for another object.
A reference is not a variable as a variable is only introduced by the declaration of an object. An object is a region of storage and, in C++, references do not (necessarily) take up any storage.
As objects and references are distinct groups of entities in C++ so the term "reference variable" isn't meaningful.
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.
A reference variable is an alias (an alternate name) for an object. [From the C++ FAQ].
The first paragraph of the Wikipedia article could easily serve as a brief definition:
In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C.
And quoting from the same article:
C++ references differ from pointers in several essential ways:
It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.
Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.
References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor.
Further reading:
Wikipedia: Reference C++
Cprogramming.com: C++ References
Stack Overflow: Difference between pointer variable and reference variable in C++
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.
A Reference variable is an alias for the variable name.
It is different from the pointers in following ways:
You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.
Once a reference is initialized to an object, it cannot be changed to point to any another object whereas in case of pointer we can make it point to any other object at any time.
A reference must be initialized the time it is created. Pointers can be made initialized at any time.
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 is an alternative label, an alias, for the object it is initialized with. Once a reference is initialized it can not be changed to be an alternative label or alias of some other object. After the initialization the reference or the object variable may be used interchangeably.
A reference has some of the characteristics of a const pointer to an object in that it is initialized when defined. And while what it references or points to can be changed, the reference or the const pointer itself can not be changed. However since a reference is an alternative label or alias it may or may not actually exist as a data object unlike a const pointer which will probably exist unless the compiler can optimize it away. And even if a reference is created as an actual entity by the compiler, that is compiler housekeeping and should be ignored since it officially does not exist much like the man behind the curtain in the Emerald City.
The following code samples gives examples comparing and contrasting reference with pointer and const pointer:
int myInt; // create a variable of type int, value not initialized
int myInt2 = 3; // create a second variable of type int with a value of 3
int &rInt = myInt; // create a reference to the variable of type int, myInt
rInt = 5; // myInt now has a value of 5, the reference is an alias for myInt
rInt++; // myInt now has a value of 6, the reference is an alias for myInt
rInt = myInt2; // myInt now has the same value as myInt2, a value of 3
int *pInt = &rInt; // pInt points to myInt
(*pInt)++; // increments myInt
pInt++; // increments the pointer which formerly pointed to myInt
int &rInt2; // error C2530: 'rInt2' : references must be initialized
int *pInt2; // just fine, uninitialized pointer is ok
int * const pInt3; // error C2734: 'pInt3' : const object must be initialized if not extern
int * const pInt4 = &myInt; // define and initialize const pointer
pInt4 = &myInt2; // error C3892: 'pInt4' : you cannot assign to a variable that is const
There are actually two kinds of references: an lvalue reference and an rvalue reference.
An lvalue reference is the same reference in the C++ language before C++11. An rvalue reference was introduced in C++11 to allow for a reference to a temporary object to assist with doing a move rather than a copy and some other actions where a copy is the wrong approach but a move is the right approach.
For example a comparison of lvalue reference and rvalue reference in the following simple source lines. Because these are int references that means that an assignment of a non-integer value results in the compiler doing a conversion which results in a temporary variable. An rvalue reference can bind to a temporary variable and an lvalue reference can not.
// assign a double to an int causing creation of temporary
int &rIntd1 = 1.2; // error C2440: 'initializing' : cannot convert from 'double' to 'int &'
int &&rIntd2 = 1.2; // warning C4244: 'initializing' : conversion from 'double' to 'int', possible loss of data
rInt = rIntd2; // myInt from the code above now has a value of 1, 1.2 was truncated when converting from double to int
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:
Easy to understand (no address, de-reference all kinds of headache things)
Saves you a tiny bit of typing, adn thus probably less error-prone.
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
Reference variables (let a), just say for easy understanding, another name of variable (let x), which holds the same exact memory location as that of x.
int &a = x; refers that a holds same memory location as that of x.
For example, say two roommates share the same room. One friends name is x and another friends name is a. If a changes the location of the table placed in the room, from position (x,y,z) to (x1,y1,z1) then changes are visible to friend x as well and vice versa.
A reference is an alternative name for an object. A reference variable provides an alias for previously defined variables. A reference declaration consists of a base type an & a reference variable equated to a variable name.
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.