i need a way to serialize objects of different types (but the types deriving from the same class) and then deserialize them to the pointer of the base class, containing the deriving class. For example:
#include<iostream>
#include<fstream>
class One
{
public:
int a;
virtual void Func()
{
}
};
class One1: public One
{
char s[128];
void Func1(int l)
{
std::cout<<l<<'\n';
}
void Func()
{
Func1(156);
}
};
int main()
{
One* x = new One1;
x->Func();
char* y=(char*)x;
delete x;
/*std::ofstream out("test11.txt",std::ofstream::out | std::ofstream::trunc);
out.write(y,sizeof(One1));
out.close();
std::ifstream in("test11.txt",std::ifstream::in);
char* y1=new char[sizeof(One1)];
in.read(y1,sizeof(One1));*/
One* z=(One*)y/*1*/;
z->Func();
return 0;
}
This code outputs
156
156
But when I uncomment the comments (when I try to write to a file the char representation of the object and to read from this file then), the program outputs 156
and ends on segmentation fault when trying to execute z->Func();
. I checked that the content of the variable y
is different from y1
. Why?
What is the cause of that issue and how can I address it (maybe by using some special libraries)?