Serialization is the process of writing or reading an object to or from a persistent storage medium such as a disk file. Serialization is ideal for situations where it is desired to maintain the state of structured data (such as C++ classes or structures) during or after the execution of a program.
When performing file processing, the values are typically of primitive types (char, short, int, float, or double). In the same way, we can individually save many values, one at a time. This technique doesn't include an object created from (as a variable of) a class.
The MFC library has a high level of support for serialization. It starts with the CObject class that is the ancestor to most MFC classes, which is equipped with a Serialize() member function.
Let us look into a simple example by creating a new MFC project.
Step 1 − Remove the TODO line and design your dialog box as shown in the following snapshot.
Step 2 − Add value variables for all the edit controls. For Emp ID and Age mentioned, the value type is an integer as shown in the following snapshot.
Step 3 − Add the event handler for both the buttons.
Step 4 − Let us now add a simple Employee class, which we need to serialize. Here is the declaration of Employee class in header file.
class CEmployee : public CObject { public: int empID; CString empName; int age; CEmployee(void); ~CEmployee(void); private: public: void Serialize(CArchive& ar); DECLARE_SERIAL(CEmployee); };
Step 5 − Here is the definition of Employee class in source (*.cpp) file.
IMPLEMENT_SERIAL(CEmployee, CObject, 0) CEmployee::CEmployee(void) { } CEmployee::~CEmployee(void) { } void CEmployee::Serialize(CArchive& ar) { CObject::Serialize(ar); if (ar.IsStoring()) ar << empID << empName << age; else ar >> empID >> empName >> age; }
Step 6 − Here is the implementation of Save button event handler.
void CMFCSerializationDlg::OnBnClickedButtonSave() { // TODO: Add your control notification handler code here UpdateData(TRUE); CEmployee employee; CFile file; file.Open(L"EmployeeInfo.hse", CFile::modeCreate | CFile::modeWrite); CArchive ar(&file, CArchive::store); employee.empID = m_id; employee.empName = m_strName; employee.age = m_age; employee.Serialize(ar); ar.Close(); }
Step 7 − Here is the implementation of Open button event handler.
void CMFCSerializationDlg::OnBnClickedButtonOpen() { // TODO: Add your control notification handler code here UpdateData(TRUE); CFile file; file.Open(L"EmployeeInfo.hse", CFile::modeRead); CArchive ar(&file, CArchive::load); CEmployee employee; employee.Serialize(ar); m_id = employee.empID; m_strName = employee.empName; m_age = employee.age; ar.Close(); file.Close(); UpdateData(FALSE); }
Step 8 − When the above code is compiled and executed, you will see the following output.
Step 9 − Enter the info in all the fields and click Save and close this program.
Step 10 − It will save the data. Run the application again and click open. It will load the Employee information.