Class serialization

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.
LVL 8
List244Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dariusz DziaraProgrammerCommented:
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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
List244Author Commented:
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.)
rstaveleyCommented:
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:
--------8<--------
#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&);
public:
      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 << v.party;
      os << '|'; // Sparating fields with '|'
      copy(v.name.begin(),v.name.end(),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.party.clear();
      v.name.clear();
      v.age = 0;

      string record;
      if (getline(is,record)) {
            istringstream iss(record);
            if (getline(iss,v.party,'|')) {
                  string names;
                  if (getline(iss,names,'|')) {
                        istringstream iss2(names);
                        string name;
                        while (getline(iss2,name,'#'))
                              v.name.push_back(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;
            }
      }

}
--------8<--------
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

rstaveleyCommented:
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 :-)
rstaveleyCommented:
> 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).
MechanTOurSCommented:
U shall have a look at boost::serialization
http://www.boost.org/libs/serialization/doc/index.html
It have a nice "Archive" concept which permits u
to save to text / binary / xml / anything u like (if u implement a new archive)

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.