C++: how serialize/deserialize objects without any library?

Posted by Winte Winte on Stack Overflow See other posts from Stack Overflow or by Winte Winte
Published on 2012-07-10T14:43:36Z Indexed on 2012/07/10 15:15 UTC
Read the original article Hit count: 138

I try to understand how serializing/deserializing works in c++, so I want to do that without any libs. But I really stuck with that. I start with simple objects but when I try to deserilize a vector I understand that I can't get a vector without if I don't write it size before. Moreover, I don't know which format of file I should choose because if digits will be existed before size of vector I haven't chance to read it right. However it is only the vector but I also want to do that with classes and map container. My task is serialize/deserialize a objects as this:

PersonInfo
{
    unsigned int    age_;
    string name_;
    enum { undef, man, woman } sex_;
}

Person : PersonInfo 
{
    vector<Person>      children_;
    map<string, PersonInfo>     addrBook_;
}

Currently I know how to serialize simple objects in way as this:

vector<PersonInfo> vecPersonInfo;
vecPersonInfo.push_back(*personInfo);
vecPersonInfo.push_back(*oneMorePersonInfo);

ofstream file("file", ios::out | ios::binary);
if (!file) {
    cout<<"can not open file";
} else {
    vector<PersonInfo>::const_iterator iterator = vecPersonInfo.begin();
    for (; iterator != vecPersonInfo.end(); iterator++) {
        file<<*iterator;
    }

Could you please suggest how I can do this for this conplex object or a good tutorial that explain it clearly?

© Stack Overflow or respective owner

Related posts about c++

Related posts about serialization