I was just going through some codes of C++.
Where in I came across the concept of reinterpret_cast
operator.
EDIT 1 :
I know that accessing private members of a class is not recommended. But in some situations we ought to go ahead and access them. I have just put forth this question to get my concepts clear.
In the example that I referred,the private member of the Class is accessed by simply creating a structure with the same variables and then later on modified by implementing
reinterpret_cast
operator.
I have understood the usage of reinterpret_cast
operator,as in I know what it does,but I fail to understand how a structure could be used to modify the values of a private Class member.
Following is the source code which I referred:
Class:
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;
};
Structure used to access and modify private class members:
struct _Student
{
void* vptr;
int id;
float score;
};
_Student* bs3 = reinterpret_cast<_Student*>(bs2);
bs3->id = 5;
Thank you.Please correct me if I'm wrong/I couldn't put forth my question in an appropriate manner.