I'm not exactly keen on the C++ cast operators but the seemingly redundant const_cast operator has one redeeming quality that makes it useful in certain conditions.
Operator const_cast is often used for removing the const or volatile qualification of an object. For example:
void readonly(char *s);
const char *p="abc";
readonly (const_cast<char *> (p));
This is a contrived example but it shows a common usage pattern.
Not all C++ programmers are aware that const_cast can also be used for adding the const and volatile qualifier to an object. Normally, this wouldn't be required because non-const and non-volatile objects are implicitly converted to const and volatile if needed:
void readonly(const char *s);
char *p= new char;
readonly(p); //OK, p is implicitly converted to const char*
Technically, you don’t need explicit casting to make this conversion happen. However, you can add const_cast to document the fact that the argument is being converted to const:
readonly(const_cast<const char*> (p)); //explicit
Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.