Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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