Serialize and Deserialize an Object in C++
Last Updated :
02 Apr, 2024
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
Similar Reads
Deletion of array of objects in C++ Need for deletion of the object: To avoid memory leak as when an object is created dynamically using new, it occupies memory in the Heap Section.If objects are not deleted explicitly then the program will crash during runtime. Program 1: Create an object of the class which is created dynamically usi
3 min read
Passing and Returning Objects in C++ In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required to do so. Passing an Object as argument To pass an object as an argument we write the object name as the argument while
4 min read
How to Write Getter and Setter Methods in C++? In C++, classes provide a way to define custom data types that can encapsulate data and methods related to that data. Getter and setter methods are commonly used to access and modify private member variables of the class allowing for the controlled access and modification of data. In this article, w
2 min read
How to Declare a Static Variable in a Class in C++? In C++, a static variable is initialized only once and exists independently of any class objects so they can be accessed without creating an instance of the class. In this article, we will learn how to declare a static variable in a class in C++. Static Variable in a Class in C++To declare a static
2 min read
Dynamic initialization of object in C++ In this article, we will discuss the Dynamic initialization of objects using Dynamic Constructors. Dynamic initialization of object refers to initializing the objects at a run time i.e., the initial value of an object is provided during run time.It can be achieved by using constructors and by passin
4 min read
How to Find the Type of an Object in C++? In C++, every variable and object has a type. The type of an object determines the set of values it can have and what operations can be performed on it. Itâs often useful to be able to determine the type of an object at runtime, especially when dealing with complex codebases. In this article, we wil
2 min read