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)
{
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.
source
share