kyb kyb - 8 months ago 57
C++ Question

Make POD from class with virtual members

I have two classes: Parent and Derived. I want to achieve ability to save and read them from/to binary file, or transfer them. Please help with idea or code snippets how do it.

class Parent {
virtual int func1(){ return 1; }
virtual unsigned func2() = 0;
std::string asd;

class Derived : public Parent {
unsigned func2(){ return 2; }
bool boo;

Save to binary file

Parent *obj = new Derived;
write_to_file( obj, sizeof(*obj) );

Then read from file

read_from_file( obj, sizeof(*obj) );

But this method will overwrite pointers to virtual functions. So I need to create POD class without virtuals to save it and to read from file. Right? Create reflected POD class for every Derived seems not good idea.

kyb kyb

There is no direct answer to this question. You should use serialization. C++ has no native serializers, as Java or C#. But there are a lot of open-source serializers over the internet. For example boost::serialization, s11n, and many others.