My friend made this code that will access the memory of class and change the value of a private variable.
#include <iostream>
using namespace std;
class has_private_variable
{
private:
    const int member1;
public:
    has_private_variable()
    : member1(5) //initializer list. In case you haven't seen that before
    {
    }
    int getMember1()
    {
        return member1;
    }
};
int main()
{
    has_private_variable hpv;
    int tmp = hpv.getMember1();
    cout << hpv.getMember1() << endl;
    char* ptr = (char*)&hpv; //Yeah this will generate all types of warnings hopefully
    //find the actual address of the member
    while (*(int*)ptr != tmp)
        ptr++;
    int* ptr_int = (int*)ptr;
    *ptr_int = 3;
    cout << hpv.getMember1() << endl;
    //There's a joke in here about hpv.vaccinate(), but I can't be bothered to find it
    return 0;
}
The ability to do this seems like it destroy the entire point of having a private variable. Is there some method to stop a programmer from being able to access a private variable like so?
Edit:
From the comments I'm getting, my friend is invoking undefined behavior of C++. But is there someway to it so that a programmer may not be able to do this?
 
     
    