Skip to content

Instantly share code, notes, and snippets.

@PotcFdk
Created February 15, 2016 12:11
Show Gist options
  • Save PotcFdk/4bd07cbac52f23904e58 to your computer and use it in GitHub Desktop.
Save PotcFdk/4bd07cbac52f23904e58 to your computer and use it in GitHub Desktop.
Casting away const.
#include <iostream>
using namespace std;
class Class
{
public:
char c = 'c';
};
void manipulate (Class & c)
{
++c.c;
}
void manipulate2 (const Class & c)
{
Class & c2 = const_cast<Class &>(c);
++c2.c;
cout << "Original address: " << int(&c.c) << endl << "Copied address : " << int(&c2.c) << endl;
}
void display (const Class & c)
{
cout << "The char is: " << c.c << endl;
}
int main()
{
const Class c;
display (c);
//manipulate(c); // Not allowed because c is const!
manipulate2 (c); // Allowed even though c is const.
display (c);
return 0;
}
@PotcFdk
Copy link
Author

PotcFdk commented Feb 15, 2016

The char is: c
Original address: 2686783
Copied address  : 2686783
The char is: d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment