Monday, October 3, 2011

const_cast c++

General Format

const_cast < type-id > ( expression )

The const_cast is the most straightforward. You can use it to cast away const-ness of a variable. It is the only cast of the four that is allowed to cast away const-ness. Theoretically, of course, there should be no need for a const cast. If a variable is const, it should stay const.

In practice, however, you sometimes find yourself in a situation where a function is specified to take a const variable, which it must then pass to a function that takes a non-const variable. The “correct” solution would be to make const consistent in the program, but that is  not always an option, especially if you are using third-party libraries. Thus, you sometimes need to cast away the const-ness of a variable.

Here is an example:

void non_const_function(char* str) {
 * do your stuffs here

void const_function (const char* str) {
const_cast_function (const_cast <char*> (str));

A pointer to any object type or a pointer to a data member can be explicitly converted to a type that is identical except for the const, volatile qualifiers. For pointers and references, the result will refer to the original object. For pointers to data members, the result will refer to the same member as the original (uncast) pointer to data member. Depending on the type of the referenced object, a write operation through the resulting pointer, reference, or pointer to data member might produce undefined behavior.

You cannot use the const_cast operator to directly override a constant variable's constant status.

The const_cast operator converts a null pointer value to the null pointer value of the destination type.

Sample Code:

No comments:

Post a Comment