Can we reassign the reference in C++?
ri = j; // >>> Is this not reassigning the reference? <<<
No, ri
is still a reference to i
- you can prove this by printing &ri
and &i
and seeing they're the same address.
What you did is modify i
through the reference ri
. Print i
after, and you'll see this.
Also, for comparison, if you create a const int &cri = i;
it won't let you assign to that.
C++ makes possible to reassign reference?
What ref = d2
actually did was assign the value of d2
to d1
- however, it's still d1
which is referred to by ref
. Because d1
is still referred to, invoking ref.f
still prints Derived1
.
Suppose you add a data value v
to your base class - set it to 1
in d1
and 2
in d2
. Change your implementations of f
to print v
. You get something like:
#include <iostream>
using namespace std;
class Base{
public:
int v;
virtual void f(){
std::cout << "Base : v=" << v << "\n";
}
};
class Derived1 : public Base{
public:
void f(){
std::cout << "Derived1 : v=" << v << "\n";
}
};
class Derived2 : public Base{
public:
void f(){
std::cout << "Derived2 : v=" << v << "\n";
}
};
int main() {
Derived1 d1;
d1.v = 1;
Derived2 d2;
d2.v = 2;
Base& ref = d1;
ref.f();
ref = d2;
ref.f();
return 0;
}
When run this will print:
Derived1 : v=1
Derived1 : v=2
Hopefully this makes it a bit clearer.
Best of luck.
C++: Why I can change the assignment of reference on my computer?
then you can't change the object which the reference is bounded to.
I am confused by this statement
The statement tries to say, that the reference cannot be modified to refer to another object. The object that is referred can be modified.
When left hand operand of assignment is a reference, you are indirecting through the reference, and assigning the value of the referred object.
ref = b;
ref
still refers to the object named by a
. That object is modified by this assignment. After the assignment, the value of a
is 4.
r = &i; // isn't this changing r to an new object?
r
still refers to the object named by p
. That object is modified by this assignment. After the assignment, p
points to i
.
How can I change the variable to which a C++ reference refers?
This is not possible, and that's by design. References cannot be rebound.
reassigning to const reference
// cnstIntRef = b; why does this not work? "expression must be modifiable lvalue"
For the same reason as why cnstIntRef++;
doesn't work. cnstIntRef
is reference to const, and therefore the the value may not be assigned to.
If this is in general not possible, why is that
It is indeed not possible.
References are different from pointers: They are dereferenced automatically. An assignment to a reference variable is an assignment to the referred object. Just as you understand that cnstIntRef++
is analogous to (*cnstIntPtr)++
, you must also understand that cnstIntRef = a
is analogous to *cnstIntPtr = a
.
As a consequence, there is no syntax to "reassign" a reference to refer to another object. A reference always refers to exactly one object throughout its entire lifetime.
what is the meaning of the second const in
const int& const cnstIntCnstRef?
It has no meaning because it is ill-formed. Unlike to pointers, qualifiers may not be applied to references; they may only be applied to the referred type.
then how do I deal with a
std::vector<const int&>
You cannot deal with std::vector<const int&>
because const int&
is not a valid type for an element of std::vector
. Vector requires the elements to be erasable. References are not erasable.
What I need to do is set the size of it, and later in the constructor body fill in the elements.
You can use a vector of pointers instead. Or vector of std::reference_wrapper
if that's more convenient for template purposes.
push_back is out of the question since it messes up the references
push_back
won't mess up references if you reserve
first.
In C++ why is it when I reassign a reference variable to a different reference variable it creates a copy of that variable instead?
When you wrote:
conf.set_foo(b);
The following things happen:
Member function
set_foo
is called on the objectconf
.Moreover, the reference parameter named
foo_
is bound the the argument namedb
. That is,b
is passed by reference.Next, the statement
foo = foo_;
is encountered. This is an assigment statement and not an initialization. What this does is that it assigns the value referred to by the parameterfoo_
to the object referred to by the data memberfoo
(which is nothing buta
here). You can confirm this by addingstd::cout<<a;
after the call toset_foo
as shown below:
int b = 2;
conf.set_foo(b);
std::cout<<a<<std::endl; //prints 2
This is because operations on a reference are actually operations on the object to which the reference is bound. This means that when we assign to a reference, we are assigning to the object to which the reference
is bound. When we fetch the value of a reference, we are really fetching the value of the object to which the reference is bound.
Note:
Once initialized, a reference remains bound to its initial object. There is no way to rebind a reference to refer to a different
object.
Can references be reassigned?
No there is no reassignment for the references here. Just the value of y
which is referenced by r2
is assigned to x
which is referenced by r
.
To handle this situation, think of the reference as an alias of the variable it references. when you put the reference anywhere you are putting the variable itself.
You can make sure of that by the following code
#include <iostream>
int main()
{
int x = 2;
int y = 3;
int& r = x;
int& r2 = y;
r = r2;
std::cout << std::boolalpha << (&x == &r) && (&y == &r2) && (&y != &r);// gives true
}
Demo
Related Topics
What's the Difference Between _Pretty_Function_, _Function_, _Func_
Error: Passing Xxx as 'This' Argument of Xxx Discards Qualifiers
C++ Dynamic Shared Library on Linux
Why Vector≪Bool≫::Reference Doesn't Return Reference to Bool
What Is the Efficient Way to Count Set Bits At a Position or Lower
How Does Array[100] = {0} Set the Entire Array to 0
Tool to Track #Include Dependencies
Why Does the C++ Stl Not Provide Any "Tree" Containers
Do Distinct Functions Have Distinct Addresses
Why Can't I Initialize Non-Const Static Member or Static Array in Class
When Should You Use Constexpr Capability in C++11
Efficiently Load a Large Mat into Memory in Opencv
Deprecated Header ≪Codecvt≫ Replacement
Unresolved External Symbol _Imp_Fprintf and _Imp_Iob_Func, Sdl2
Calling Pthread_Cond_Signal Without Locking Mutex
Calculate the Factorial of an Arbitrarily Large Number, Showing All the Digits