Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
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 24-Dec-12 2:33am

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
Comments
vikuseth at 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 at 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)

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 437
1 sanket saxena 355
2 thatraja 240
3 Abhinav S 216
4 CPallini 215
0 Sergey Alexandrovich Kryukov 8,784
1 OriginalGriff 5,025
2 Peter Leow 3,839
3 Maciej Los 3,535
4 Er. Puneet Goel 3,107


Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 24 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid