The C++ const_cast usage demonstrating the const variable converted to the normal variable

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Modifying the constant variable declared by const keyword

To show: The const_cast usage to convert the const to the normal variable

 

 

// Demonstrates const_cast

#include <iostream>

using namespace std;

 

int main(void)

{

// p = 10 is a constant value, cannot be modified

const int p = 20;

cout<<"const p = "<<p<<"\nq = p + 20 = "<<(p + 20)<<endl;

// The following code should generate error, because

// we try to modify the constant value...

// uncomment, recompile and re run, notice the error...

// p = 15;

// p++;

 

// remove the const and rebuild, rerun...

int r = const_cast<int> (p);

// the value of 10 should be modified now...

--r;

cout<<"Removing the const, decrement by 1,\nNew value = "<<r<<endl;

}

 

Output example:

 

const p = 20

q = p + 20 = 40

Removing the const, decrement by 1,

New value = 19

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index