| vikuseth (19) | |||
I was just learning some c++ concept and met with the above 2 concepts . Can anyone please explain the concept i marked as error in the above 2 sample program ? | |||
|
|
|||
| TTT (52) | |
|
In first program you've written int *j = const_cast<int*>(i); That is, you're trying to cast from const int to int* - that is error In second program int j = const_cast<int>(i);Here you're trying to cast from int value which is not for example pointer or reference. That is, it is the same if you write int j = const_cast<int>(9);and you'll get the same error | |
|
Last edited on
|
|
| dexter4life (22) | |||||
I Guess the operator const_cast works only for pointers and reference. Converting objects and variables to temporal const and returning the result to the assignment operator. int j = const_cast<int&>(i) is a constant reference or alias. While this,
Here, at the second code, 'i' is just a variable and not a pointer. Therefore, converting it to a pointer through const_cast is a bad thing. But using the ampersand operator as in the first works Ok; Since the ampersand returns a pointer and const_cast is converting it into a pointer. But a constant pointer. | |||||
|
|
|||||
| Cubbi (1927) | ||
That pretty much sums it: const_cast can only cast pointers to pointers and lvalues to references. Here's a more detailed description: http://en.cppreference.com/w/cpp/language/const_cast | ||
|
|
||