Created
March 16, 2017 09:09
-
-
Save IvanIvanoff/8055c78456b2d11b98d34ad92825fd5b to your computer and use it in GitHub Desktop.
Mutate private data of a class though a pointer of a class with the same memory layout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example program | |
#include <iostream> | |
#include <string> | |
class X | |
{ | |
int x; //private | |
int y; // private | |
public: | |
void print() const { std::cout << x << " " << y << std::endl;} | |
}; | |
class Z | |
{ | |
public: | |
int x; | |
int y; | |
}; | |
int main() | |
{ | |
X x; | |
Z* z; | |
z = (Z*)&x; | |
z->x = 100; | |
z->y = 200; | |
x.print(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment