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 rules1.
but: replacing casts union
makes code standard-compliant; guaranteed work in c++11:
#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; }; union pu { point p; pointhack ph; pu(int x, int y) : p(x, y) {} }; int main() { pu u(4,5); u.p.print(); u.ph.x=1; u.ph.y=2; u.p.print(); return 0; }
this comes fact point
, pointhack
standard-layout classes2 (c++11, §9 ¶7), , share "common initial subsequence" (§9.2, ¶20); such, if both stored in same union (here pu
) it's permitted "inspect common initial part of of them"3.
still, answer exercise of style; don't exploit such tricks unless forced to. c++ provides better means access private members if necessary without brutally breaking encapsulation - have getters/setters, protected inheritance, friend classes, ... , in general, if access private class members in ways not intended target class, potentially violating assumptions of class how data modified, can lead erratic behavior of code of methods.
notes:
- in c++ can't have 2 pointers of unrelated types pointing same object; restriction used optimizers assumptions aliasing.
- notice requirements quite stringent; typically classes aren't c structs don't qualify this. having different access qualifiers can break magic.
- the idea assigning
ph
makes "active object" ofunion
, ,p.print()
1 "inspecting" "inactive" object.
Comments
Post a Comment