Skip to content

Instantly share code, notes, and snippets.

@mikehelmick
Last active August 29, 2015 13:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mikehelmick/9634526 to your computer and use it in GitHub Desktop.
In our series of how C++ doesn't actually offer you any protection in the language, we show how you can directly access private member variables. Don't try this at home. Ok - do try this at home, and then don't do it at work.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Point {
public:
void setX(int newX) {
x = newX;
}
void setY(int newY) {
y = newY;
}
int getX() const {
return x;
}
int getY() const {
return y;
}
void printAddrs() const {
cout << "&x: " << &x << " &x: " << &y << endl;
}
string toString() const {
stringstream ss;
ss << "(" << getX() << "," << getY() << ")";
return ss.str();
}
private:
int x;
int y;
};
int main() {
Point p;
p.setX(4);
p.setY(6);
cout << "size of a Point: " << sizeof(Point) << endl;
cout << "&p " << &p << endl;
p.printAddrs();
// Get a pointer to p
Point* pPtr = &p;
// Cast this to an int pointer
int* ptr = (int*) pPtr;
// Start interpreting the member variables from the base address
cout << "x = " << *ptr << endl;
cout << "y = " << *(ptr + 1) << endl;
// Worse! - Change the member variables through pointer mainpulation!
*ptr = 32;
*(ptr + 1) = 33;
cout << "point: " << p.toString() << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment