Search code examples
c++serialization

How to write/read into/from file mode ios::binary with derived class?


I have 2 classes, Employee and derived classes productEmployee. Here is implement:

class employee:

class Employee
{
protected:
    char name[100];
public:
    Employee();//char[100] -> don't declare anything
    virtual ~Employee();//char[100] -> don't delete anything

    virtual float getSalary() = 0;
    virtual void input();//input to name
    virtual void print();//print name
};

class productEmployee:

class productEmployee :
    public Employee
{
protected:
    int product;
public:
    productEmployee() :Employee(){
        product = 0;
    }
    ~productEmployee();//don't delete anything

    float getLuong() {
        return 150000 * product;
    }
    void input() {
        NhanVien::input();
        cin >> product;
    }
    void print() {
        NhanVien::print();
        cout << "Product: " << product;
        cout << "Salary: " << getSalary() << endl;
    }
};

in main.cpp

    string file = "data.dat";
    productEmployee a, b;

    a.input();
    ofstream fout(file, ios::binary);
    fout.write((char*)&a, sizeof(a));//write object a
    fout.close();

    ifstream fin(file, ios::binary);
    fin.seekg(0, ios::beg);
    fin.read((char*)&b, sizeof(b));//read object a --> b
    fin.close();

    b.print();

It work well, I type "12345" and 10. But when I comment from a.input() to fout.close(), mean only this code run(I want to read like that)

    string file = "data.dat";
    productEmployee b;
    ifstream fin(file, ios::binary);
    fin.seekg(0, ios::beg);
    fin.read((char*)&b, sizeof(b));//read object a --> b
    fin.close();

    b.print();

b.print() only run well NhanVien::print() and count<<product, when into like getSalary(), debug show error:

Exception thrown: read access violation.
this-> was 0x7FF624BE7290.

and I also don't understand meaning address of __vfptr it has values 0x00007ff624be7290{???,???,???,???,???}

So, how can I read this binary file without write first (code worked well when we write above like cell3 here, but only read like cell4 is not working..)


Solution

  • I Solved my problem:(Maybe like that) when I write to object, I don't write virtual table of that, so when I read object from file, this NhanVienSanXuat b don't have virtual table so it had some error, so i only need to use NhanVien *c = b.clone(), c have value we had and also have virtual table, so it works well!