const_cast Casting Operator Explained With Simple Example

This is one of the most dangerous casting operators. The “const_cast” operator is used to remove the const or volatile property of a variable. The target-type and source-type must be of the same type here.

Normal syntax to do const_cast is as follows:

const_cast <target-type> (expr)

target-type and expr must be of same type pointer or reference.

Important Points

  • const_cast used to remove const-ness of a pointer or reference.
  • target-type and expr must be of same type pointer or reference.
  • const_cast is a dangerous feature and hence must be used with caution.

Let’s have a look at the sample program to understand const_cast operator functionality.

#include <iostream>

void demo_const_cast_pointer (const int *val)
{
	int *p;

	p = const_cast <int *> (val);
	*p = *val * 10;
}

void demo_const_cast_reference (const int &val)
{
	int &p = const_cast <int &> (val);

	p = p * 20;
}

int main ()
{
	/* Check for const_cast */
	int val = 5;
	cout << "Initial value: " << val << endl;
	demo_const_cast_pointer (&val);
	cout << "After using const_cast_pointer: " << val << endl;
	demo_const_cast_reference (val);
	cout << "After using const_cast_reference: " << val << endl;
}

Let’s analyze the output of above program.

Initial value: 5
After using const_cast_pointer: 50
After using const_cast_reference: 1000

Leave a Reply

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