C++ - Change private member from outside the class -
is code causes undefined behavior? or can run problem this? (copy full class without functions, variables public modifier , modify private memebers throw pointer) example: #include <iostream> using namespace std; class point { private: int x; int y; public: point(int x, int y) { this->x = x; this->y = y; } void print() { cout << "(" << x << ", " << y << ")" << endl; } }; struct pointhack { int x; int y; }; int main() { point a(4, 5); a.print(); ((pointhack *) (&a))->x = 1; ((pointhack *) (&a))->y = 2; a.print(); return 0; } output: (4, 5) (1, 2) (with original member order, of course) despite classes being layout compatible (see below), code exhibits undefined behavior due fact such pointer casts prohibited the c++ strict aliasing rules 1 . but: replacing casts union makes code st...