EQuestionAnswers.com Computer/Electronics Questions and Answers
C, C++, VC++, COM/DCOM, DLL and more
#Login #Sign up  Facebook Twitter TGoogle+
 

#Previous question #Index of VC++/WIN32/MFC Questions #Next question

Serialization

Serialization is the process of reading or writing an object to or from a stream. This stream can be a storage medium like a disk file, stream or socket file. Serialization is necessary for situations where it is desired to maintain the state of an object (object of C++ classes or structures). Program can store the data members of the object in file and exit if needed. Later it can load the members in the same way it was saved and thus maintain the same state of the object as before. Serialization is not limited to disk file. File stream can be in the form of network socket or byte stream for serial line or in any other form.

Need of Serialization

An object with members of primitive types such as char, short, int, float, or double can be stored with easy file operations. Members are saved serially one by one and can be retrieved in the same sequence. Saving an C++/MFC object is some what different from this traditional structured approache. MFC class object can contain another objects like CString, CArray. These objects are of variable lenghts. Again we need to takecare both save and restore of parent class before do the same for current class. MFC defines an uniform way to save and restore any object to or from file stream and this support is there from top level CObject in the MFC hiararchy. Any object that supports Serialization should call the parent class Serialization routine before processing its own members. Thus the entire hiararchy state members of the object are saved and restored. MFC also defines uniform ways to CString, CArray and other variable length objects.

Serialization implementation

It starts with the CObject class that is the ancestor to most MFC classes, which is equipped with a Serialize() member function. The class should declare with the macros DECLARE_SERIAL(< class name >) and also should add implement macro IMPLEMENT_SERIAL(< class name >, < parent class name >, < Schema version >). The class should implement Serialize(CArchive&) routine and it should save and restore class members in this routine. Let us look into a simple example by creating a new MFC project. Here we declared a class called CStudent to store and retrieve fields of a student. It contains standard, enrollment number, name, marks and age. This demo application is based on a dialog box which retrieves these files when "Open" button is pressed. It reads and shows these fields. User can enter new values and save those with "Save" button.

Source Code

/* ---CStudent class in Student.h--- */
class CStudent : public CObject
{
public :
  CStudent(void);
  ~CStudent(void);
  WORD    m_wStd;
10    WORD    m_wRoll;
11    CString m_sName;
12    double  m_dMarks;
13    WORD    m_wAge;
14 
15  public :
16    void Serialize(CArchive& ar);
17 
18    DECLARE_SERIAL(CStudent);
19  };
20 
21  /* ---CStudent class in Student.cpp--- */
22 
23  IMPLEMENT_SERIAL(CStudent, CObject, 0)
24  CStudent::CStudent(void)
25  {
26  }
27  CStudent::~CStudent(void)
28  {
29  }
30  void CStudent::Serialize(CArchive& ar)
31  {
32    CObject::Serialize(ar);
33    if( ar.IsStoring() ) {
34      ar << m_wStd << m_wRoll << m_sName << m_dMarks << m_wAge;
35    } else {
36      ar >> m_wStd >> m_wRoll >> m_sName >> m_dMarks >> m_wAge;
37    }
38  }
39  /* ---CStdDialogDlg in StdDialogDlg.h--- */
40 
41  class CStudentDlg : public CDialog
42  {
43  public :
44    /* standard constructor */
45    CStudentDlg(CWnd* pParent = NULL);
46 
47    enum { IDD = IDD_STDDIALOG_DIALOG };
48 
49  protected :
50    CStudent m_Student;
51    /* DDX/DDV support */
52    virtual void DoDataExchange(CDataExchange* pDX);
53    virtual BOOL OnInitDialog();
54    afx_msg void OnOpen();
55    afx_msg void OnSave();
56 
57    DECLARE_MESSAGE_MAP()
58  };
59  /* ---CStdDialogDlg in StudentDlg.cpp--- */
60  CStudentDlg::CStudentDlg(CWnd* pParent /*=NULL*/)
61      : CDialog(CStudentDlg::IDD, pParent)
62  {
63 
64    /* Set default initial values */
65    m_Student.m_sName = "";
66    m_Student.m_wStd = 1;
67    m_Student.m_wRoll = 1;
68    m_Student.m_dMarks = 100;
69    m_Student.m_wAge = 5;
70  }
71  void CStudentDlg::DoDataExchange(CDataExchange* pDX)
72  {
73    CDialog::DoDataExchange(pDX);
74    DDX_Text(pDX, IDC_NAME, m_Student.m_sName );
75    DDX_Text(pDX, IDC_STD, (short&)m_Student.m_wStd );
76    DDX_Text(pDX, IDC_ROLL, (short&)m_Student.m_wRoll );
77    DDX_Text(pDX, IDC_MARKS, m_Student.m_dMarks );
78    DDX_Text(pDX, IDC_AGE, (short&)m_Student.m_wAge );
79  }
80  BEGIN_MESSAGE_MAP(CStudentDlg, CDialog)
81    ON_COMMAND(ID_SAVE, OnSave)
82    ON_COMMAND(ID_OPEN, OnOpen)
83  END_MESSAGE_MAP()
84 
85  BOOL CStudentDlg::OnInitDialog()
86  {
87    CDialog::OnInitDialog();
88    return TRUE;
89  }
90  void CStudentDlg::OnSave() 
91  {
92    UpdateData(TRUE);
93    CFile file;
94    file.Open("student.dat", CFile::modeCreate | CFile::modeWrite);
95    CArchive ar(&file, CArchive::store);
96    m_Student.Serialize(ar);
97    ar.Close();
98    file.Close();
99  }
100  void CStudentDlg::OnOpen() 
101  {
102    CFile file;
103    file.Open("student.dat",  CFile::modeRead);
104    CArchive ar(&file, CArchive::load);
105    m_Student.Serialize(ar);
106    ar.Close();
107    file.Close();
108    UpdateData(FALSE);
109  }
110  /* ---CStdDialogApp in StdDialogApp.h--- */
111 
112  class CStdDialogApp : public CWinApp
113  {
114  public :
115    CStdDialogApp();
116    virtual BOOL InitInstance();
117  };
118  /* ---CStdDialogApp in StdDialogApp.cpp--- */
119 
120  /* CStdDialogApp construction */
121 
122  CStdDialogApp::CStdDialogApp()
123  {
124  }
125  /* CStdDialogApp app object */
126  CStdDialogApp theApp;
127  /* CStdDialogApp initialization */
128  BOOL CStdDialogApp::InitInstance()
129  {
130    CStudentDlg dlg;
131    m_pMainWnd = &dlg;
132    int nResponse = dlg.DoModal();
133    if (nResponse == IDOK)
134    {
135    }
136    else if (nResponse == IDCANCEL)
137    {
138    }
139    return FALSE;
140  }

Output

Student records serialization demo app

You have viewed 1 page out of 109. Your VC++ learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

#Programming Windows, Fifth Edition (Developer Reference)
#Programming Applications for Microsoft Windows (Microsoft Programming Series)
#Programming Windows with MFC, Second Edition
#Visual C++ Programming
#Programming Microsoft Visual C++, Fifth Edition

* #1 webmaster Sat 26 Apr/2014 22:42:47(GMT)  Like 0 Unlike 0

Dear Users,

We are pleased to inform you that a forum/blog has been incorporated with www.mybestnotes.co.in. You are welcomed to add your comments, requests, codes, solutions and feedback to it. Please login(if already a member) or signup(for free) to avail to this facility.

Regards,
Webmaster

Your message goes here:

Name:Guest
Email:anonymous@unknown.com
My Post:*
Secutiry Code: ******  *
Preview this compose before posting this in discussion forum.
 
Note:
  1. Use [Sxx] code to show smiles. Example [S02]
  2. Use [URL ], example [URL http://www.google.com/]
  3. To display code or un formatted text use [CODE] [/CODE]. Example: [CODE] printf("Hello world"); [/CODE]
 [S01]   [S02]   [S03]   [S04]   [S05]   [S06]   [S07]   [S08] 
 [S09]   [S10]   [S11]   [S12]   [S13]   [S14]   [S15]   [S16] 
 [S17]   [S18]   [S19]   [S20]   [S21]   [S22]   [S23]   [S24] 

Note: Only members are allowed, * fields are mandatory.