Another const_cast C++ program example in modifying the const object 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 const variable by using const_cast modifier
To show: The C++ const_cast usage in modifying the const object variable
// Demonstrates the const_cast
#include <iostream>
using namespace std;
struct One
{
// test function
void funct1()
{ cout<<"Testing..."<<endl;}
};
// const argument, cannot be modified...
void funct2(const One& c)
{
// will generate warning/error...
c.funct1();
}
int main(void)
{
One b;
funct2(b);
return 0;
}
Output example:
There will be error message during the program building. Change c.funct1(); to the following statements recompile and rerun the program.
// remove the const...
One &noconst = const_cast<One> (c);
cout<<"The reference = "<<&noconst<<endl;
Rebuild and re-run the program. The following output should be expected.
The reference = 0012FF63
Press any key to continue . . .