×

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations.

C++ supports the four types of casting operators listed below:

  • const_cast
  • static_cast
  • dynamic_cast
  • reinterpret_cast

const_cast is a type casting operator. It is used to update the constant value of any item or to eliminate the constant feature of any item.

Const_cast can be utilized in programmes that contain any object with a constant value that needs to be updated at some time.

Syntax:

The following is the syntax:

const_cast<type name>(statement)

Example 1

Input:

const int a = 50;
const int* b = &a;
cout << " The previous is" << *b << "\n";
int* c = const_cast <int * > (b);
*c=100;
cout << "The current value is" << *b;

Output:

The previous value is 50
The current value is 100

The following example demonstrates the fundamental use of const_cast. We've declared a constant variable "a" of type int with a value of 50 and another constant pointer "b" of type int that points to the variable "a."

To use const_cast, a third pointer must be generated, which we have done above using pointer "c" of the same data type, int.

So, we can alter the value of our constant pointer "y" by sending our constant pointer "b," which points to the constant variable "a," into const =_cast and assigning a value to the pointer z.

If we try to change the value of "a" that the pointer "b" is pointing at without using const_cast, we will get the error "assignment of read-only location".

1. const_cast

const_cast is used to eliminate variables' constness. Here are some interesting facts about const cast.

Const_cast can be used within a const member function to modify non-const class members. Evaluate the code below. The compiler treats 'this' as 'const student* const this' inside const member function fun(), i.e. 'this' is a constant reference to a constant object, and hence the compiler does not allow changing the data members via the 'this' pointer. const_cast converts the pointer 'this' to'student* const this'.

C++ Program:

#include <iostream>
using namespace std;
class student_abc
{
private:
	int rollofabc;
public:
	student_abc ( int r1 ):rollofabc ( r1 ) {}
	void fun() const
	{
		( const_cast <student_abc*> (this) )->rollofabc = 7;
	}


	int getRollofabc () { return rollofabc; }
};
int main(void)
{
	student_abc s1 (2);
	cout << "The previous roll number: " << s1.getRollofabc() << endl;
	s1.fun();
	cout << "The current roll number: " << s1.getRollofabc() << endl;
	return 0;
}

Output:

The previous roll number: 2
The current roll number: 7

2. const_cast is a function that can be used to pass const data to a function that does not receive const. For example, in the following software, fun() receives a standard pointer, but const_cast allows a pointer to a const to be supplied.

C++ Program:

#include <iostream>
using namespace std;


int fun ( int* ptr00 )
{
	return ( *ptr00 + 12 );
}
int main ( void )
{
	const int value = 12;
	const int *ptr00 = &value;
	int *ptr01 = const_cast <int *>( ptr00 );
	cout << fun (ptr01);
	return 0;
}

Output:

24

3. Modifying a value that was first specified as const is unspecified behaviour. Consider the program below. The program's output is undefined. The variable 'value' is a const variable, and the function 'fun(ptr01)' attempts to alter it with const_cast.

C++ Program:

#include <iostream>
using namespace std;


int fun(int* ptr00)
{
	*ptr00 = *ptr00 + 12;
	return (*ptr00);
}


int main(void)
{
	const int value = 12;
	const int *ptr00 = &value;
	int *ptr01 = const_cast <int *>(ptr00);
	fun(ptr01);
	cout << value;
	return 0;
}

Output:

12 (Unspecified Behavior)

It is permissible to change a value that was not initially specified as const. For example, in the preceding program, removing the const from the definition of value causes the programme to print 24.

C++ Program:

#include <iostream>
using namespace std;
int fun(int* ptr00)
{
	*ptr00 = *ptr00 + 12;
	return (*ptr00);
}
int main(void)
{
	int value = 12;
	const int *ptr00 = &value;
	int *ptr01 = const_cast <int *>(ptr00);
	fun(ptr01);
	cout << value;
	return 0;
}

Output:

24

4. Const cast is thought to be secure than simple type casting. It's secure in the respect that casting will not occur if the type of cast is not the same as the initial object. For instance, the following code refuses to compile because 'int *' is typecast to 'char *'.

C++ Program:

#include <iostream>
using namespace std;


int main(void)
{
	int x1 = 20;
	const int* y1 = &x1;
	char* z1 = const_cast <char *> (y1); 
	*z1 = 'X';
	return 0;
}

Output:

/tmp/7pb22V979A.cpp: In function 'int main()':
/tmp/7pb22V979A.cpp:8:36: error: invalid const_cast from type 'const int*' to type 'char*'
    8 |  char* z1 = const_cast <char *> (y1); // compiler error
      |                                    

5. We can also use const cast to eliminate a volatile attribute from a variable. For example, in the following code, b1's typeid is PVKi (reference to a volatile and constant integer), but c1's typeid is Pi (Pointer to integer).

C++ Program:

#include <iostream>
#include <typeinfo>
using namespace std;


int main(void)
{
	int a1 = 40;
	const volatile int* b1 = &a1;
	cout << "typeid of b1 " << typeid(b1).name() << '\n';
	int* c1 = const_cast <int *> (b1);
	cout << "typeid of c1 " << typeid(c1).name() << '\n';
	return 0;
}

Output:

The typeid of y1 PVKi
The typeid of z1 Pi

Related Topics

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

C++ Program to find largest subarray with 0 sum

Write a program to find the largest subarray that has a sum zero. The array contains positive and negative numbers. Print the length of the max subarray whose sum turns...

4 minutes read.

Malloc() and new in C++

In C ++, malloc () and new are used for the same thing. During runtime, they are used to allocate memory. Malloc () and the new, on the other hand,...

4 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.