Open In App

Serialize and Deserialize an Object in C++

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, serialization is the process of converting an object into a sequence of bytes so that it can be stored in memory or transmitted across a network and deserialization is the reverse process, where the byte stream is used to reconstruct the original object. In this article, we will learn how we can serialize and deserialize an object in C++.

What is Object Serialization?

Serialization is the process of converting an object of a particular class into a stream of bytes in such a way that we can reconstruct the exact same object at later times. The process of reconstructing the serialized object is called deserialization. It is generally used to store it in the memory or transmit it over a network.

Need for Serialization of Object in C++

Serialization is needed when we need to store the state of the structure data such as classes and structes in C++.

Generally in C++, when we write data in binary form to files using fwrite(), it will simply convert all the data in the given object to binary and store it in the memory as it is. Due to this, members that may refer to the dynamic memory will not be copied. Also, if the class contains the virtual functions, it may not work correctly when reconstructed.

So, serialization is needed for the proper conversion and storage of the given objects so that they can be properly reconstructed.

Note: The serialization of POD data is same as storing in binary form. So, the fwrite() function works well for the serialization of POD data including POD classes.

How to Serialization and Deserialization an Object in C++?

We can serialize an object either using the inbuilt fstream class with custom serialization function or we can use the external libraries such as boost serialization that provides robust method of serialization.

In this article, we will perform serialization and deserialization using the fstream class:

Approach

  • First, create a class for the object you want to serialize and deserialize and it should have data members that hold the object’s state.
  • Now, implement the method in the class to serialize the object and write its data to a file named data.bin.
    • In this method, we will be using the ofstream::write() method to write the data in the binary form.
  • Implement the static method to deserialize the object from the file and reconstruct it using the ifstream::read() method.
  • In the main method, serialize the data again deserialize it, and then print it.

C++ Program to Serialize and Deserialize an Object in C++

The below program illustrates how we can serialize and deserialize an object in C++.

C++
// C++ Program to illustrate how we can serialize and
// deserialize an object
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

class Serializable {
private:
    string name;
    int age;

public:
    Serializable(){};
    // Constructor to initialize the data members
    Serializable(const string& name, int age)
        : name(name)
        , age(age)
    {
    }

    // Getter methods for the class
    string getName() const { return name; }
    int getAge() const { return age; }

    //  Function for Serialization
    void serialize(const string& filename)
    {
        ofstream file(filename, ios::binary);
        if (!file.is_open()) {
            cerr
                << "Error: Failed to open file for writing."
                << endl;
            return;
        }
        file.write(reinterpret_cast<const char*>(this),
                   sizeof(*this));
        file.close();
        cout << "Object serialized successfully." << endl;
    }

    //  Function for Deserialization
    static Serializable deserialize(const string& filename)
    {
        Serializable obj("", 0);
        ifstream file(filename, ios::binary);
        if (!file.is_open()) {
            cerr
                << "Error: Failed to open file for reading."
                << endl;
            return obj;
        }
        file.read(reinterpret_cast<char*>(&obj),
                  sizeof(obj));
        file.close();
        cout << "Object deserialized successfully." << endl;
        return obj;
    }
};

int main()
{
    // Create and serialize an object
    Serializable original("Alice", 25);
    original.serialize("data.bin");

    // Deserialize the object
    Serializable restored
        = Serializable::deserialize("data.bin");

    // Test the  deserialized object
    cout << "Deserialized Object:\n";
    cout << "Name: " << restored.getName() << endl;
    cout << "Age: " << restored.getAge() << endl;

    return 0;
}


Output

Object serialized successfully.
Object deserialized successfully.
Deserialized Object:
Name: Alice
Age: 25






Like Article
Suggest improvement
Next
Share your thoughts in the comments

Similar Reads