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 ?

Here is the first statement explained:

[cast to non-const int pointer] ( [get a pointer to 'i' (const)] );
       const_cast<int*>         (               &i               );

Here is the second statement explained:

[cast to non-const int pointer] ( [get value of 'i'] );
       const_cast<int*>         (          i         );

The error is because an integer value is not a pointer value, and so, the const_cast cannot do that cast. It can only map pointers to pointers, or references to references.

Here is the third statement explained:

[cast to non-const int reference] ( [implicitly get a reference to 'i' (const)] );
        const_cast< int& >        (                      i                      );

Here is the second statement explained:

[cast to non-const int value] ( [get value of 'i' (const)] );
       const_cast< int >      (              i             );

The error is because the const_cast cannot be used to cast between values, only between pointers or references. For values, we talk about "conversions" not casts. As in:

int i_nc = i;  // OK: no need for const-cast since the value is copied.

A conversion is a method to copy the value of an object of one type into an object of another type. Casting operators don't make sense for that purpose.

Very well explained ..Thanks brother .Now i got the concept...:)

This article has been dead for over six months. Start a new discussion instead.