Click here to Skip to main content
13,559,785 members
Rate this:
Please Sign up or sign in to vote.
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 24-Dec-12 2:33am

1 solution

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

Solution 1

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
double &val = 66.6; //illegal
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web02-2016 | 2.8.180527.1 | Last Updated 24 Dec 2012
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100