0
votes
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));
2

2 Answers

2
votes

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).

1
votes

The language does not allow use of &this as an expression since (https://timsong-cpp.github.io/cppwp/n3337/class.this#1)

the keyword this is a prvalue expression

You can use the addressof (&) operator only on lvalue expressions.

More importantly, you need to use

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

to save the object.