Last active
November 21, 2022 02:19
-
-
Save schellingb/5506678176948fa82494d128b95b9876 to your computer and use it in GitHub Desktop.
Safest hack to access private data of a C++ class
This file contains 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
/* | |
Access C++ Private Member | |
License: Public Domain (www.unlicense.org) | |
Based on http://cpp.kjx.cz/private_backdoor.html which itself is based on http://bloglitb.blogspot.com/2011/12/access-to-private-members-safer.html | |
*/ | |
#include <stdio.h> | |
class CSafe | |
{ | |
int data; | |
}; | |
namespace CSafePrivate | |
{ | |
template<int CSafe::*MEMBER_PTR> struct _DataTemplate | |
{ | |
inline friend int& Data(CSafe& obj) { return obj.*MEMBER_PTR; } | |
}; | |
template struct _DataTemplate<&CSafe::data>; | |
inline int& Data(CSafe& obj); | |
} | |
int main() | |
{ | |
CSafe a; | |
CSafePrivate::Data(a) = 20; | |
printf("Data: %d\n", CSafePrivate::Data(a)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment