I’m trying to access and modify the private data member of a class by offset.
AFAIK, first thing is to calculate the offset, then access the member through the offset.
Here is my code.
class Test {
public:
int a;
int b;
private:
int c;
};
Test test;
cout << *(&test + &Test::b + 1); // access c
I got an error : “+” operator invalid, the right operand contains “int Test::*” type.
There is a similar post, it printf the offset of abas 1,4, but when try like this:
cout << &Test::a << '\t' << &Test::b;
I got 1 1.
My question:
1. Why cout got the wrong result?
2. What does Test::*p point to?
3. How to access and modify the Test::* pointer?(Or how to access the private member when doesn’t know the offset?)
This works:
But the offset should be known. In the above
ptris type oftestand thereforeptr++will increment the pointer value tosizeof (test). Because the location of the private membercis at the end and is a type of integer so one integer step is decreased by castingptrintoint *first and then decrementing 1, which now points to the address ofc. It is printed first, and next the value ofcis modified by first castingptrtoint *and then assigning a value, and then printed.It is not guaranteed that it will always get the value of
cwhen you know the position ofcas the padding might be different in other cases. Also there is no point accessing a private data member because at the time of the object design approach it was made to be accessed by the member functions and is a tool for organization by providing abstraction. When implementing such a concept in other languages like C, which does not have object oriented features, you can implement such a private – public environment by personally following a convention, but the compiler will not enforce anything if you accessed a “private” where you actually shouldn’t. But in C++ the compiler provides the restriction and stops you from diverting and breaking the object orientated design which you made. At run time all’s in memory and you can access them without any restriction from your code at that time nothings private or public. If you know how to interpret the bytes in the executable you can change anything you like, even the code itself. I do not think this is a good idea to be implemented, as it will make the code unpredictable and unportable and definitely violate the OOD approach.