[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Class serialization

Posted on 2006-04-21
6
Medium Priority
?
381 Views
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.
0
Comment
Question by:List244
6 Comments
 
LVL 8

Accepted Solution

by:
mrblue earned 400 total points
ID: 16516106
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.

0
 
LVL 8

Author Comment

by:List244
ID: 16520713
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.)
0
 
LVL 17

Assisted Solution

by:rstaveley
rstaveley earned 400 total points
ID: 16523593
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<--------
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 17

Expert Comment

by:rstaveley
ID: 16523620
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 :-)
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 16523773
> 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).
0
 
LVL 2

Assisted Solution

by:MechanTOurS
MechanTOurS earned 400 total points
ID: 16554943
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)

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses

872 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