Sample_Program-1
#include<iostream>
usingnamespace std ;
int main(){
constint i = 9;
int *j = const_cast<int*>(&i); //Ok
int *j = const_cast<int*>(i); //Error
}
Sample_Program-2
#include<iostream>
usingnamespace std ;
int main(){
constint i = 9;
int j = const_cast<int&>(i);//Ok
int j = const_cast<int>(i);//Error
}
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 ?
int j = const_cast<int&>(i);//Ok
int j = const_cast<int>(i);//Error
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,
1 2 3
constint i = 9;
int *j = const_cast<int*>(&i); //Ok
int *j = const_cast<int*>(i); //Error
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.