const_cast in C++

In this tutorial, we will learn const_cast in C++ with examples.

There are 4 types of casting operators as follows:

1. const_cast
2. static_cast
3. dynamic_cast
4. reinterpret_cast

Here we have explained about const_cast in c++.

const_cast is one of the casting operators supported by C++.  It is used to remove the constant nature of an object in C++.

Syntax:

const_cast<type name>(expression)

Example:

Input: 
const int a = 67; 
const int* b = &a; 
cout<<"Previous Value of a:"<<*b<<"\n";
int* c=const_cast<int *>(b); 
*c=109; 
cout<<"New Value of a:"<<*b;
Output:
Previous Value of a:67
New Value of a:109

Some other uses of const_cast:

const_cast can be used to pass constant variables to a function that does not accept constant parameters.

#include <bits/stdc++.h>
using namespace std;
int func(int* a) {
   return (*a + 4);
}
int main() {
   const int var = 16;
   const int *add = &var;
   int *z = const_cast <int *>(add);
   int y = func(z);
   cout << y;
   return 0;
}
Output: 20

Here, notice that we cannot change the value of const variable which is being passed, it will give the error ‘Undefined Behaviour’.

#include <bits/stdc++.h> 
using namespace std; 
int func(int* a) 
{ 
*a=*a+56;
return (*a); 
} 
int main() 
{ 
const int var = 16; 
const int *add = &var; 
int *z = const_cast <int *>(add); 
int y = func(z) ;
cout << var; 
return 0; 
}
Output: Undefined Behaviour

It is acceptable to modify variable which is not declared constant.

Also read: How to use dynamic_cast on vector in C++

Leave a Reply

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