const_cast operator in C++

const_cast operator in C++

How is const_cast operator used in C++?

Explanation

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

Example :

#include 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;
example(c);
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.





Leave a Reply

Your email address will not be published. Required fields are marked *