const_cast in C++ | Type Casting operators
Last Updated :
23 Aug, 2018
C++ supports following 4 types of casting operators:
1. const_cast
2. static_cast
3. dynamic_cast
4. reinterpret_cast
1. const_cast
const_cast is used to cast away the constness of variables. Following are some interesting facts about const_cast.
1) const_cast can be used to change non-const class members inside a const member function. Consider the following code snippet. Inside const member function fun(), ‘this’ is treated by the compiler as ‘const student* const this’, i.e. ‘this’ is a constant pointer to a constant object, thus compiler doesn’t allow to change the data members through ‘this’ pointer. const_cast changes the type of ‘this’ pointer to ‘student* const this’.
#include <iostream>
using namespace std;
class student
{
private :
int roll;
public :
student( int r):roll(r) {}
void fun() const
{
( const_cast <student*> ( this ) )->roll = 5;
}
int getRoll() { return roll; }
};
int main( void )
{
student s(3);
cout << "Old roll number: " << s.getRoll() << endl;
s.fun();
cout << "New roll number: " << s.getRoll() << endl;
return 0;
}
|
Output:
Old roll number: 3
New roll number: 5
2) const_cast can be used to pass const data to a function that doesn’t receive const. For example, in the following program fun() receives a normal pointer, but a pointer to a const can be passed with the help of const_cast.
#include <iostream>
using namespace std;
int fun( int * ptr)
{
return (*ptr + 10);
}
int main( void )
{
const int val = 10;
const int *ptr = &val;
int *ptr1 = const_cast < int *>(ptr);
cout << fun(ptr1);
return 0;
}
|
Output:
20
3) It is undefined behavior to modify a value which is initially declared as const. Consider the following program. The output of the program is undefined. The variable ‘val’ is a const variable and the call ‘fun(ptr1)’ tries to modify ‘val’ using const_cast.
#include <iostream>
using namespace std;
int fun( int * ptr)
{
*ptr = *ptr + 10;
return (*ptr);
}
int main( void )
{
const int val = 10;
const int *ptr = &val;
int *ptr1 = const_cast < int *>(ptr);
fun(ptr1);
cout << val;
return 0;
}
|
Output:
Undefined Behavior
It it fine to modify a value which is not initially declared as const. For example, in the above program, if we remove const from declaration of val, the program will produce 20 as output.
#include <iostream>
using namespace std;
int fun( int * ptr)
{
*ptr = *ptr + 10;
return (*ptr);
}
int main( void )
{
int val = 10;
const int *ptr = &val;
int *ptr1 = const_cast < int *>(ptr);
fun(ptr1);
cout << val;
return 0;
}
|
4) const_cast is considered safer than simple type casting. It’safer in the sense that the casting won’t happen if the type of cast is not same as original object. For example, the following program fails in compilation because ‘int *’ is being typecasted to ‘char *’
#include <iostream>
using namespace std;
int main( void )
{
int a1 = 40;
const int * b1 = &a1;
char * c1 = const_cast < char *> (b1);
*c1 = 'A' ;
return 0;
}
|
output:
prog.cpp: In function ‘int main()’:
prog.cpp:8: error: invalid const_cast from type 'const int*' to type 'char*'
5) const_cast can also be used to cast away volatile attribute. For example, in the following program, the typeid of b1 is PVKi (pointer to a volatile and constant integer) and typeid of c1 is Pi (Pointer to integer)
#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:
typeid of b1 PVKi
typeid of c1 Pi
Exercise
Predict the output of following programs. If there are compilation errors, then fix them.
Question 1
#include <iostream>
using namespace std;
int main( void )
{
int a1 = 40;
const int * b1 = &a1;
char * c1 = ( char *)(b1);
*c1 = 'A' ;
return 0;
}
|
Question 2
#include <iostream>
using namespace std;
class student
{
private :
const int roll;
public :
student( int r):roll(r) {}
void fun() const
{
( const_cast <student*> ( this ) )->roll = 5;
}
int getRoll() { return roll; }
};
int main( void )
{
student s(3);
cout << "Old roll number: " << s.getRoll() << endl;
s.fun();
cout << "New roll number: " << s.getRoll() << endl;
return 0;
}
|
—Aashish Barnwal.
Similar Reads
reinterpret_cast in C++ | Type Casting operators
reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different.It does not check if the pointer type and data pointed by the pointer is same or not. Sy
3 min read
Casting Operators in C++
The casting operators is the modern C++ solution for converting one type of data safely to another type. This process is called typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer). Let's take a look at an example: [G
5 min read
C/C++ Ternary Operator - Some Interesting Observations
Predict the output of following C++ program. #include <iostream> using namespace std; int main() { int test = 0; cout << "First  character " << '1' << endl; cout << "Second character " << (test ? 3 : '1') << endl; return 0; } One would ex
3 min read
Conversion Operators in C++
In C++, the programmer abstracts real-world objects using classes as concrete types. Sometimes, it is required to convert one concrete type to another concrete type or primitive type implicitly. Conversion operators play an important role in such situations. It is similar to the operator overloading
4 min read
ios operator() function in C++ with Examples
The operator() method of ios class in C++ is used to any error flag of this stream is set. This includes the failbit or the badbit. Syntax: operator void*() const; Parameters: This method does not accept any parameter. Return Value: This method returns a null pointer if any error bit is set of this
1 min read
ios operator() function in C++11 with Examples
The operator() method of ios class in C++11 is used to any error flag of this stream is set. This includes the failbit or the badbit. Syntax: explicit operator bool() const; Parameters: This method does not accept any parameter. Return Value: This method returns false if any error bit is set of this
1 min read
Copy Constructor vs Assignment Operator in C++
Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them: Copy constructor Assignment operator It is called when a new object is created from an existing object, as a copy of the exist
2 min read
Difference between Type Casting and Type Conversion
1. Type Casting: In type casting, a data type is converted into another data type by the programmer using the casting operator during the program design. In type casting, the destination data type may be smaller than the source data type when converting the data type to another data type, that's why
3 min read
typeid operator in C++ with Examples
typeid is an operator in C++. It is used where the dynamic type or runtime type information of an object is needed.It is included in the <typeinfo> library. Hence inorder to use typeid, this library should be included in the program.The typeid expression is an lvalue expression. Syntax: typeid
3 min read
iswctype() function in C/C++
The iswctype() is a built-in function in C/C++ which checks if a given wide character has a certain property. It is defined within the cwctype header file of C/C++ Syntax: int iswctype(wint_t wc, wctype_t desc) Parameter: The function accepts two mandatory parameter which are described below: wc - T
2 min read