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:
#include
class SeeminglyImmutableInteger {
private:
int value;
public:
SeeminglyImmutableInteger(int value) {
this->value = value;
}
};
int main() {
SeeminglyImmutableInteger* notSoImmutableInteger = new SeeminglyImmutableInteger(10);
int* privateInt = (int*)notSoImmutableInteger;
std::cout << *privateInt << std::endl;
(*privateInt) *= 42;
std::cout << *privateInt << std::endl;
}
And as you can see, the so called ‘immutable’ integer technically isn’t immutable.
% g++ single.cpp && ./a.out
10
420
Another way to do the same thing is to create a struct with the same internal data types. For instance:
struct MutableInteger {
public:
int value;
};
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.