const_cast in c++  is used to cast away the constness and volatility of a variables. const_cast is used to remove the const-ness from references and pointers that ultimately refer to something that is not const. so it not allowed to cast away variables those are originally constant. Let us see a example.

In the above example we are casting away the constness of pointer b and reference a. The pointer b and reference a are pointing to a non const variable x.

  • It would be undefined behavior if we cast away the constness of pointer or  reference those are pointing to a const variables. Let us see below program.

Try to compile above program. it will compile without any error. try to run , it will error out core dumped at runtime. So if a variable in c++ is const , it should never be changed.

A simple use case of const_cast in c++

Let see below sample program.

  • Let us compile the above program and see what errors come

The error says that the program tries a conversion from const int* to int * because our foo function expects a non const pointer. so what should be options …

We have to take a const pointer from variable x, remove the constness of pointer and pass to the function foo().

  • It is safe to use const_cast in place of simple cast.

The cast would give compile time error if the type of cast is not same as original variable.

  • const_cast example to cast away volatile-ness of a variable.


Related Contents to follow