const_cast operator in C++

How is const_cast operator used in C++?


const_cast operator is used to add or remove a "const" modifier from a type.

Example :

#include <iostream.h> using namespace std; void example(const float &a)
float &b = const_cast (a);
b = 20.0;
} int main()
float c = 17.5;
cout << "The value before const_cast is:: " << c << endl;
cout << "The value after const_cast is::" << c << endl;
return 0;

Result :

The value before const_cast is:: 17.5
The value after const_cast is:: 20

In the above example the const_cast operator is used in a function to assign a constant value as "20.0". So that whenever the function is called the "20.0" is returned.

C++ Tutorial

Ask Questions

Ask Question