Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

About assigning to references

Status
Not open for further replies.

maluk

Programmer
Oct 12, 2002
79
SG
I am reading about C++ references. I came about the code that cannot compile. Here is the code:

Code:
int& i = 1 ;       // this will cause a compiler error
const int& j = 1 ; // this works

On my compiler, it says Initialization of non-const reference type 'int&' from rvalue of type 'int'. Can someone tell me the reason for this? What does it say in the C++ Standard regarding this?

Just for clarification, is the numeric literal '1' a constant?


Rome did not create a great empire by having meetings, they did it by
killing all those who opposed them.

- janvier -
 
In C++ reference initializer must be one of:
1. lvalue (except a bit-field)...
2. has a class type (to bind directy) and can be implicitly converted to an lvalue of ref. type...
3. otherwise, the reference shall be to a non-volatile const type.

You have rule #3 violation...

Semantics: 1 is not an object in memory, it's integer one value. You can't redefine integer one via reference to 1. But:
Code:
/* if */ int& oneref = 1; // is OK, and oneref refers to 1
/*then*/ oneref = 2; // is OK too, but now 2 == 1?
 
Apropos, it's not an assigning to reference, it's a reference initialization. Assigning != initialization.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top