Search code examples
c++objectfile-handlingostreamthis-pointer

Using this pointer to write object to binary file in c++


void Employee::store_data(string filename) {
    fstream file;
    file.open(filename,ios::app | ios::binary);
    if (file) {
        file.write((char*)&this,sizeof(this));
        file.close();
    }
    else cout<<"\n Error in Opening the file!";

}

this is what i tried. I want to store the current object of employee class to a file in binary mode. but i get this this

error: lvalue required as unary '&' operand
     file.write((char*)&this,sizeof(this));

Solution

  • this isn't an actual variable, so you can't take its address. But it already is a pointer, so you don't need to. It also has size of a pointer, so your sizeof is wrong. And then in C++ you should not use C-style casts. So fixing these 3 things, your line becomes

    file.write(reinterpret_cast<char*>(this), sizeof(*this));
    

    That should compile.

    However, note that if Employee contains anything complex, such as std::string member variables, pointer member variables, virtual methods, constructor / destructor etc, you can't read the data back. That write doesn't in that case write everything, or writes wrong runtime values, and you get garbage back. You enter the dreaded Undefined Behavior territory, anything can happen (including things apparently working when you test it).