Class serialization

Posted on 2006-04-21
Last Modified: 2013-12-14
I have a couple questions, first, what are common methods of serializing a class?

Second, why serialize a class?  Serializing a class, if I am not mistaken would cause the class to only allow one
instance rather than several due to the fact that it would load and save instances, making two separate serialized
instances impossible.
Question by:List244
    LVL 8

    Accepted Solution

    There is Serialize() method in MFC with CArchive parameter. CArchive has methods and operators to easily write object data member values to some stream (file for instance). There are COM interfaces for serialization, deserialization of COM/ActiveX objects like IPersistStorage interface with methods Load() & Save().

    "Second, why serialize a class?" - to save object state in some persistent storage like file.

    "I am not mistaken would cause the class to only allow one" - I don't see a reason. You create object, initialize it with some values, serialize its internal state & store data to file (SAVE). Then you can destroy object, recreate it and initialize from the stream you previously used as storage (LOAD). You can create other object and again initialize its state from the same stream (again LOAD). You also can to initialize object manually.

    LVL 8

    Author Comment

    Mr.Blue, I am hoping for a little more input on the subject from some of the other experts, I have not abandoned the question.
    If there is no further input, I will accept your answer sometime next week.  If there is other input, you can expect a splitting of
    points.  (I like to hear different points of views on things.)
    LVL 17

    Assisted Solution

    XML is worth considering for class serialisation. You deal with class composition with nested elements. It is of course more expensive than MFC's binary approach. If you can affort the processing text-based serialisation is much more transparent.

    Mostly I serialise lists of simple objects using '\n' to delimit objects and '|' to delimit fields. That of course only works when fields do not contain '\n' or '|'. It makes it easy to find the nth object using a text editor on the serialisation file - just look for the nth line.

    Here's a simple demo, which you'll notice doesn't attempt to do anything clever with class composition:
    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <algorithm>
    #include <iterator>
    #include <vector>
    using namespace std;

    class voter;
    ostream& operator<<(ostream&,const voter&);
    istream& operator>>(istream&,voter&);

    class voter {
          string party;
          vector<string> name;
          int age;
          friend ostream& operator<<(ostream&,const voter&);
          friend istream& operator>>(istream&,voter&);
          voter() {}
          voter(const string& party,const vector<string>& name,int age) : party(party),name(name),age(age) {}
          template<typename Iterator>
          voter(const string& party,Iterator begin,Iterator end,int age) : party(party),name(begin,end),age(age) {}

    ostream& operator<<(ostream &os,const voter& v)
          os <<;
          os << '|'; // Sparating fields with '|'
          copy(,,ostream_iterator<string>(os,"#")); // Separating names with '#'
          os << '|' << v.age << '\n';; // Using '\n' as the end of record marker
          return os;

    istream& operator>>(istream &is,voter& v)
          v.age = 0;

          string record;
          if (getline(is,record)) {
                istringstream iss(record);
                if (getline(iss,,'|')) {
                      string names;
                      if (getline(iss,names,'|')) {
                            istringstream iss2(names);
                            string name;
                            while (getline(iss2,name,'#'))
                iss >> v.age;
          return is;

    int main()
          const char *names[] = {"Mary","Mungo","Midge"};
          voter v("Green",names,names+sizeof(names)/sizeof(char*),77);
          cout << v;

                ofstream fout("file.dat",ios::ate|ios::app);
                fout << v;

                ifstream fin("file.dat");
                while (fin >> v) {
                      cout << v;

    LVL 17

    Expert Comment

    You can go quite a ong way with this approach, but as you can see the voter class contains a vector of names and serialisation requires a different delimiter for the names (it uses '#' rather than '|'). XML parsing means you don't have to keep contriving different delimiters, but makes an Experts Exchange posting rather longer :-)
    LVL 17

    Expert Comment

    > Second, why serialize a class?  

    Let's be pedantic here. You serialise objects not classes. You serialise them so that you can keep them or so that you can move them from one place to another (e.g. squirt them through a socket).
    LVL 2

    Assisted Solution

    U shall have a look at boost::serialization
    It have a nice "Archive" concept which permits u
    to save to text / binary / xml / anything u like (if u implement a new archive)


    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
    Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
    The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
    The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now