Home > Blogs > 30 C++ Tips in 30 Days: Tip # 8 use const_cast to add cv qualification, not just remove it

30 C++ Tips in 30 Days: Tip # 8 use const_cast to add cv qualification, not just remove it

By  Nov 26, 2007

Topics: Programming, C/C++

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[12];
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

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.