Casting a const to a non const (C++)

Started by
1 comment, last by Xai 19 years, 4 months ago
I know that this will be considered poor programming, but the fact that I can compile under these circumstances raises the question... When I have a method that takes a constant (pointer in this case): void SomeMethod( const SomeObject* object) { ... } and somewhere in that method I pass that parameter to another method that uses the same pointer only in non-const form... If I don't explicitly cast the pointer, I get compile errors (expected) but if I do cast it to a non-const pointer: ... NewMethod( (SomeObject*)object ); ... it compiles fine. Will this cause problems down the road? If a const can be cast to a non-const, doesn't this defeat the purpose? Thanks, Chris Z.
Chris Z. GPU FX
Advertisement
Quote:Original post by ZeroEffect
Will this cause problems down the road?
Only if one of the functions attempts to modify an essentially const object. It's sad that so much code still flouts const correctness...

Quote:If a const can be cast to a non-const, doesn't this defeat the purpose?
const_cast exists specifically for this reason.
You will get no errors from casting away const, you will only get errors based on what you actually do to the object ... so if you do something to the object that is illegal in this case (for instance try to change the contents of a const char * that is in code space), or simply change a value when the client program is 100% expecting you won't (cause you promised you wouldn't with the const label) - and therefore in the client's eyes, you function would have a bug. But as has been said, if your are passing to an old function that takes a non-const parameter, but doesn't actually modify the parameter, then no problems will ever occur (until the day that other function releases a new version that DOES modify the parameter - and ruins your day).

This topic is closed to new replies.

Advertisement