Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
const_cast in C++ | Type Casting operators
Next article icon

const_cast in C++ | Type Casting operators

Last Updated : 23 Aug, 2018
Comments
Improve
Suggest changes
Like Article
Like
Report
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'. CPP
#include <iostream> using namespace std;  class student { private:     int roll; public:     // constructor     student(int r):roll(r) {}      // A const function that changes roll with the help of const_cast     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. CPP
#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. CPP
#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. CPP
#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 *' C
#include <iostream> using namespace std;  int main(void) {     int a1 = 40;     const int* b1 = &a1;     char* c1 = const_cast <char *> (b1); // compiler error     *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) CPP
#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 CPP
#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 CPP
#include <iostream> using namespace std;  class student { private:     const int roll; public:     // constructor     student(int r):roll(r) {}      // A const function that changes roll with the help of const_cast     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.

Next Article
const_cast in C++ | Type Casting operators

K

kartik
Improve
Article Tags :
  • C Language
  • C++
Practice Tags :
  • CPP

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:C++#
    5 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
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences