Got confused with const_cast

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Sample_Program-1

#include<iostream>
using namespace std ;

int main(){
const int i = 9;
 int *j = const_cast<int*>(&i); //Ok 
 int *j = const_cast<int*>(i);  //Error
}

Sample_Program-2

#include<iostream>
using namespace std ;

int main(){
const int 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 ?

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
1
2
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
const int 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.
const_cast works only for pointers and reference

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


Topic archived. No new replies allowed.