Class Private members modified when creating a structure (C ++)

I was just looking through some C ++ codes. Where I came across the concept of operator reinterpret_cast.

EDIT 1:

I know that access to private members of a class is not recommended. But in some situations, we must go forward and turn to them. I just formulated this question to understand my concepts.

In the example that I called, the private member of the class is accessed simply by creating a structure with the same variables, and then subsequently with a change through implementation reinterpret_cast.

I understood the use of the operator reinterpret_cast, since I know what it does, but I don’t understand how the structure can be used to change the value of a member of a private class .

Below is the source code that I named:

Grade:

class Student
{
public:
    explicit Student(float percent) // Cannot be used for conversion
    {
        static int nid;

        id = ++nid;
        score = percent;
    }

    int Id() const
    {
        return id;
    }

    float GetScore() const
    {
        return score;
    }

    void SetScore(float value)
    {
        score = value;
    }

    virtual ~Student(){}

private:
    int id;
    float score;
};

The structure used to access and modify private members of a class:

struct _Student
    {
        void* vptr;
        int id;
        float score;
    };

    _Student* bs3 = reinterpret_cast<_Student*>(bs2);
    bs3->id = 5;

Thank. Please correct me if I am wrong / I could not ask my question accordingly.

+3
source share
5 answers

$5.2.10/2 - " , , ; ."

, 'bs2' 'bs3'

$9.2/16 - " ( 9) ( ) (3.9)."

, .

$9/6-

- :

- ( ) ,

- (10.3) (10.1),

- ( 11) ,

- ,

-

- , .108

, .

'void *', , , 'vptr' ( , , )

reinterpret_cast (bs2) (bs3). . (. ), , ( ).

. ! , , undefined

+3

.

, , ?

, . - -go. , , , friend .

++ : , , . undefined (.. , ) .

tl; dr: Dont. -.

Caveat. : , / , . (?), . .

+3

, , , . , , , . , reinterpret_cast .

reinterpret_cast, , , -:

unsigned short Hash( void *p ) {

unsigned int val = reinterpret_cast<unsigned int>( p );
return ( unsigned short )( val ^ (val >> 16));

} >

:

static_cast, dynamic_cast, const_cast reinterpret_cast?

http://advancedcppwithexamples.blogspot.com/2010/02/reinterpretcast-in-c.html

http://www.linuxtopia.org/online_books/programming_books/thinking_in_c++/Chapter03_054.html

+2

.

, .

, , ( - ) .

+1

, , - . , "friend". , reinterpret_cast, , Student struct _Student, , . , , :

int* bs3 = reinterpret_cast<int*>(bs2);
++bs3;
*bs3 = 5;

, .

+1

Source: https://habr.com/ru/post/1767137/


All Articles