I just discovered reinterpret_cast in C++ and I am trying to learn more about it. I wrote this code:
struct Human{
    string name;
    char gender;
    int age;
    Human(string n, char g, int a) : name(n), gender(g), age(a) {}
};
int main()
{
    Human h("John", 'M', 26);
    char* s = reinterpret_cast<char*>(&h);
    Human *hh = reinterpret_cast<Human*>(s);
    cout << hh->name << " " << hh->gender << " " << hh->age << endl;
}
It works pretty well, exactly as expected. Now I want convert the char * to an std::string and then from this string get back the Human object:
int main()
{
    Human h("John", 'M', 26);
    char* s = reinterpret_cast<char*>(&h);
    string str = s;
    Human *hh = reinterpret_cast<Human*>(&str);
    cout << hh->name << " " << hh->gender << " " << hh->age << endl; // prints wrong values
}
Does anyone have an idea to overcome this ?
Thank you.
 
    