I wonder why this isn`t working.Code:const int a = 10; int b; b = const_cast <int> (a);
How to make a simple non const copy of a const variable?
I wonder why this isn`t working.Code:const int a = 10; int b; b = const_cast <int> (a);
How to make a simple non const copy of a const variable?
You can't change consts. But all it takes to make a copy is reading the value, and of course you can do that.Code:int b = a;
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
No way?
I could write it to a file and then read it... But... You know....
No more elegant way?
He means that you can't change consts.
About the only thing the const keyword does is prevent code from compiling when a const is used as an l-value.
Basically this means:
Not very complicated unfortunately.Code:const int a = 10; // a = 20; won't compile int b = a; // OK
My memory was that
brings a compile error can not convert from const int to int. But somehow I really messed up.Code:const int a = 5; int b = a;
Solved, Thanks.
Const just means you can't change the original memory, but since you're making a copy of the given value at memory, it works fine.
Problem comes when passing pointers around. Since they all point to the original memory, you can't pass a const pointer where a normal pointer is expected.
Though it is possible to do away with const for such things as pointers. But they do put the implementation at risk, so do it with care.