Skip to content

Instantly share code, notes, and snippets.

@schellingb
Last active November 21, 2022 02:19
Show Gist options
  • Save schellingb/5506678176948fa82494d128b95b9876 to your computer and use it in GitHub Desktop.
Save schellingb/5506678176948fa82494d128b95b9876 to your computer and use it in GitHub Desktop.
Safest hack to access private data of a C++ class
/*
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