How to access private C++ members.

So, I was just thinking about how C++ is really stored in memory, and realized that private class variables are not private at all, in reality.

When a class is stored in memory, all of the member variables are simply stored in a big blob of data. So in theory, if you simply typecast a pointer to a class to another type, pointer arithmetic could be done to access any member variable.


Here is a simple example:



And as you can see, the so called ‘immutable’ integer technically isn’t immutable.


Another way to do the same thing is to create a struct with the same internal data types. For instance:

Then, all you have to do is typecast the SeemingleImmutableInteger into a MutableInteger.

Of course this shouldn’t ever be used in practice, but I thought it was interesting.



Leave a Reply

Your email address will not be published. Required fields are marked *