Reputation: 4022
I think most would be surprised about the topic again, However I am referring to a book "C++ Common Knowledge: Essential Intermediate Programming" written by "Stephen C. Dewhurst".
In the book, he quotes a particular sentence (in section under Item 5. References Are Aliases, Not Pointers), which is as below
A reference is an alias for an object that already exists prior to the initialization of the reference. Once a reference is initialized to refer to a particular object, it cannot later be made to refer to a different object; a reference is bound to its initializer for its whole lifetime
Can anyone please explain the context of "cannot later be made to refer to a different object"
Below code works for me,
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int i = 100;
int& ref = i;
cout<<ref<<endl;
int k = 2000;
ref = k;
cout<<ref<<endl;
return 0;
}
Here I am referring the variable ref
to both i
and j
variable.
And the code works perfectly fine.
Am I missing something? I have used SUSE10 64bit linux for testing my sample program.
Thanks for your input in advance.
Upvotes: 1
Views: 272
Reputation: 263118
#include <iostream>
int main()
{
int i = 100;
int& ref = i;
int k = 2000;
ref = k;
if (&ref == &i) std::cout << "ref is bound to i\n";
if (&ref == &k) std::cout << "ref is bound to k\n";
}
Upvotes: 2
Reputation: 21108
The line ref = k
is not changing what ref
is referring to, it is assigning the value of k
to the value of ref
. If you subsequently print i
you will find that i
is now 2000 as well.
Upvotes: 5
Reputation: 258148
You aren't binding ref
to another object: when you do ref = k
, it is as though you did i = k
, which simply reassigned the value of i
. In other words, you're calling i
's operator=
.
Here's something that better demonstrates the idea:
#include <iostream>
int main()
{
std::ostream& stream = std::cout;
stream = std::cerr; // fails to compile! Cannot access ostream::operator=
return 0;
}
Upvotes: 11