How to break through the access rights of C + + classes through pointers


See the following code

#include "pch.h"
#include <iostream>
using namespace std;
class A {
 A(int a, int b,int c) :m_a(a), m_b(b),m_c(c) {};
 int m_a, m_b,m_c;
int main()
 A obj( 1, 2, 3);
 int a = obj.m_a; //Compile error
 A *p = new A(3,4,5);
 int b = p->m_ b; // Inaccessible

Because m in a_ A and M_ B is private, so it cannot be accessed.

But this is only inaccessible at the syntax level. We can still access private and protected in the class through pointers.

Assume that the memory model of object obj is:

The starting address is 0x1000, because they are all int integer types, so m_ a、m_ b、m_ C are 4 bytes apart, so the starting address + the number of bytes apart can access the address of the member variable.

If M_ B is public, then

int b = p->m_b;

Is correct. At this time, the internal conversion of the compiler is: int b = * (int *) ((int) P + sizeof (int));

1. P is the pointer to the object obj

2. (int) P converts the pointer to int type for addition

3. Sizeof (int) is the byte length occupied by int, which is used to calculate the offset of m_b

4. (int) P + sizeof (int) gets M_ B, but it is of type int at this time, so it is cast to type int * through (int *)

5. The * at the beginning is to obtain the data on the address

In this way, the above error code can be written as:

int a = *(int*)(&obj);
int b = *(int*)( (int)p + sizeof(int) );
/*-------Access variable m_ c--------*/
int c =*(int*)( (int)p + sizeof(int)*2 );

In this way, you can break through the access restrictions (other types are similar)


The above is how to break through the access rights of C + + classes through pointers. I hope it will help you!