If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Re: Got confused with const_cast

My compiler gives only error message but dont explain it . I am new to c++ . Thats why i have mentioned in my post "Can anyone please explain the conpt i marked as error in the above 2 sample program ?"

Re: Got confused with const_cast

Well, for your first example (once I fix an irrelevant error whereby you declare j twice), my compiler complains that there was an:

Code:

invalid const_cast from type 'const int' to type 'int*'

Doesn't that explain to you what is the problem? The problem is that the const_cast is invalid. Why is it invalid? Because a const_cast is supposed to be used to remove (or add) const-ness, but here you are also changing from a non-pointer type to a pointer type.

For your next example, I get:

Code:

invalid use of const_cast with type 'int', which is not a pointer, reference, nor a pointer-to-data-member type

This tells you that the const_cast is invalid because what you are trying to cast "is not a pointer, reference, nor a pointer-to-data-member type".

So, did you actually read the error messages that your compiler gave you and tried to make sense to what they said?

Re: Got confused with const_cast

So constant cast only works for pointer , reference or pointer to datamember ?

Consider your second example. You could have done without a cast:

Code:

int j = i;

The fact that i is const does not matter since its value is copied to j.

On the other hand, consider:

Code:

const int x = 123;
const int* i = &x;
int* j = i;

Now this is a problem, because you could potentially write:

Code:

*j = 456;

which would result in undefined behaviour since you're changing a constant. However, maybe for some reason (e.g., working with a legacy API) you really do need j to be an int*, not a const int*, but you know for sure that the value will not be changed through the pointer. In that case, it is appropriate to write: