Removing the const-ness (constant-ness) of the 'this' pointer in C++
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: Removing the constant-ness of the this pointer that point to an object in C++
To show: How to remove the const-ness of the 'this' pointer in C++ programming
// Removing the const-ness of the 'this' pointer
#include <iostream>
using namespace std;
class Test
{
public:
void GetNumber(int);
// Read only function...
void DisplayNumber() const;
private:
int Number;
};
void Test::GetNumber(int Num)
{Number = Num;}
void Test::DisplayNumber() const
{
cout<<"\nBefore removing const-ness: "<<Number;
const_cast<Test>(this)->Number+=2;
cout<<"\nAfter removing const-ness: "<<Number<<endl;
}
int main(void)
{
Test p;
p.GetNumber(20);
p.DisplayNumber();
return 0;
}
Output example:
Before removing const-ness: 20
After removing const-ness: 22
Press any key to continue . . .