Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
double &val = 66.6; //illegal
const double &val = 66.6; //legal
I was just doing some demo programs and came through the above concept but not able to identify what exactly the need of the above concept . what magic exactly const is doing in the second case ?
can anyone please let me know where exactly we can use this concept in real time programming ?
Posted

1 solution

Quote:
const double &val = 66.6; //legal
You may use a constant only as rvalue hence there is no need for val to refer to an actual address (that is the compiler may implicitly substitute every occurrence of val with the constant 66.6).

Note you cannot apply the same argument to the
Quote:
double &val = 66.6; //illegal
line.
 
Share this answer
 
Comments
vikuseth 24-Dec-12 11:00am    
int nVar = 12;
int &rVar = nVar ;//Ok
double &dVar = nVar ;//Error
const double &cdVar = nVar ;//Ok

can you please explain Why the 3rd statement is not working where as 4th statement is working ?
Philippe Mori 25-Dec-12 9:32am    
It is not the same type thus you cannot have a int reference to a double as the representation is different. A reference is essential another name for the same variable.
The reason why it work when const is added is simply because you cannot modify a const object. Since you cannot modify cdVar, it means that nVar will not be modified and since it not modified, then you can take a copy and convert it and it won't matter.

The other way... If you modify rVar, then nVar is also modified. Thus is is legal. But for dVar, since it is not the same variable (not the same type) a modification to dVar would not be reflected in nVar. This is why it is not allowed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900