Problem:
I wrote an object into a file in binary mode using std::fstream
. However, when I read it back from that file to another object and then call one of the virtual member functions of this new object, there's a memory access violation error.
Here's what the code looks like:
class A
{
public:
// data
virtual void foo() = 0;
};
class B: public A
{
public:
// added data
virtual void foo() { ... }
}
int main()
{
// ...
A* a = new B();
A* b = new B();
file.write((char*)a, sizeof(B));
// ...
thatSameFile.read((char*)b, sizeof(B));
b->foo(); // error here
}
What I've figured out:
After a couple of hours debugging, I see that the __vfptr
member of b
(which, as far as I know, is the pointer to the virtual table of that object) is changing after the file read statement. I guess that not only did I write the data of a
to file and copy those to b
, I also copied the virtual table pointer of a
to b
.
Is what I said correct? How can I fix this problem?