0
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 ?

2
Contributors
2
Replies
3
Views
4 Years
Discussion Span
Last Post by vikuseth
1

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.

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.