×

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

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.

How to improve programming skills in C++

Before getting started, one should know why to improve their programming skills. To become a good software developer or programmer, one must be skilled in at least one programming language. Many...

4 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

fscanf() Function in the C++

In the C++ programming language, the fscanf() method can be used to read data from a file stream. Syntax: The syntax for the fscanf() function in the C++ programming language is as...

3 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

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.

10 Best C and C++ Books for Beginners & Advanced Programmers

If you want to become a skilled software developer, you should never stop learning, whether you're a working professional or a student. Why, therefore, only C or C++? The fundamental...

6 minutes read.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

C++ Tricks for Competitive Programming

If you are interested in Computer science or Information technology, you must have heard about competitive programming. Competitive programming is a way to improve your problem-solving skills. There are various...

7 minutes read.

Containership in C++

In C++, it is possible to create an object in one class into another class, and that object is a member of another class. This relationship is known as a...

4 minutes read.

C++ Pipe Tutorial

A pipe is a mechanism for inter-process communication (IPC) in a Unix-like operating system. It allows two or more processes to communicate with each other by sending and receiving data...

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.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.