Serialization in C++ refers to the process of converting an object into a format that can be stored or transmitted (usually to a file or over a network) and later reconstructed (deserialized) back into an object. Object serialization is especially useful when you need to save the state of an object to disk or send it across a network for later use.
C++ does not have built-in serialization support like other languages (e.g., Java), so we often need to manually implement serialization using object streams. Serialization typically involves converting the object data to a byte stream, and deserialization involves reading the byte stream back and reconstructing the object.
In this process, you use object streams (std::ofstream and std::ifstream) along with overloaded stream insertion (<<) and extraction (>>) operators to handle the serialization and deserialization of object data.
The process of serializing an object involves converting its data members into a sequence of bytes that can be saved or transmitted. The insertion operator (<<) is overloaded to define how to write an object to a stream (serialization), while the extraction operator (>>) is overloaded to define how to read an object from a stream (deserialization).
Serialization can be done using text-based streams (e.g., std::ofstream, std::ifstream). This format is human-readable and often used when you want to debug or transfer simple object data.
#include <iostream>
#include <fstream>
using namespace std;
// Class definition
class Person {
private:
string name;
int age;
public:
// Constructor to initialize the object
Person(string n = "", int a = 0) : name(n), age(a) {}
// Getter functions for name and age
string getName() const { return name; }
int getAge() const { return age; }
// Overloading the << operator for serialization (output to file)
friend ostream& operator<<(ostream& out, const Person& p) {
out << p.name << endl; // Write name
out << p.age << endl; // Write age
return out;
}
// Overloading the >> operator for deserialization (input from file)
friend istream& operator>>(istream& in, Person& p) {
getline(in, p.name); // Read name
in >> p.age; // Read age
in.ignore(); // Ignore the newline character left by >> operator
return in;
}
};
int main() {
// Create a Person object
Person p1("Alice", 30);
// Serialization: Write the object to a file
ofstream outFile("person.txt");
outFile << p1; // Use overloaded << operator to write object
outFile.close();
// Deserialization: Read the object back from the file
Person p2;
ifstream inFile("person.txt");
inFile >> p2; // Use overloaded >> operator to read object
inFile.close();
// Output the deserialized object data
cout << "Name: " << p2.getName() << ", Age: " << p2.getAge() << endl;
return 0;
}
Person class has two data members: name (string) and age (int).<<) writes the data of the Person object to an output stream (ofstream).>>) reads the data from an input stream (ifstream) to reconstruct the Person object.getline() function is used to read the string name because it may contain spaces, while the >> operator is used to read the integer age.Output (content of "person.txt"):
Alice
30
Console Output:
Name: Alice, Age: 30
Binary serialization uses ofstream and ifstream with the ios::binary flag to read and write objects in a binary format, which is more efficient than text-based serialization. Binary serialization stores data in its raw binary form, making it compact and faster for large data.
#include <iostream>
#include <fstream>
using namespace std;
// Class definition
class Person {
private:
string name;
int age;
public:
Person(string n = "", int a = 0) : name(n), age(a) {}
// Getter functions for name and age
string getName() const { return name; }
int getAge() const { return age; }
// Serialization to binary file
void writeBinary(ofstream& out) const {
size_t nameLength = name.size();
out.write(reinterpret_cast<const char*>(&nameLength), sizeof(nameLength)); // Write name length
out.write(name.c_str(), nameLength); // Write name
out.write(reinterpret_cast<const char*>(&age), sizeof(age)); // Write age
}
// Deserialization from binary file
void readBinary(ifstream& in) {
size_t nameLength;
in.read(reinterpret_cast<char*>(&nameLength), sizeof(nameLength)); // Read name length
name.resize(nameLength);
in.read(&name[0], nameLength); // Read name
in.read(reinterpret_cast<char*>(&age), sizeof(age)); // Read age
}
};
int main() {
// Create a Person object
Person p1("Bob", 25);
// Serialization: Write object to a binary file
ofstream outFile("person_binary.dat", ios::binary);
p1.writeBinary(outFile);
outFile.close();
// Deserialization: Read object from a binary file
Person p2;
ifstream inFile("person_binary.dat", ios::binary);
p2.readBinary(inFile);
inFile.close();
// Output the deserialized object data
cout << "Name: " << p2.getName() << ", Age: " << p2.getAge() << endl;
return 0;
}
writeBinary() method serializes the Person object into a binary format:
name string (as a size_t), followed by the string itself.age.readBinary() method deserializes the object from the binary format:
name string, then the string itself.age.Binary file contents are not human-readable, as the data is stored in raw binary format.
| Aspect | Text Serialization | Binary Serialization |
|---|---|---|
| Readability | Human-readable | Not human-readable |
| File Size | Larger (due to text representation) | Smaller (compact binary format) |
| Performance | Slower (due to formatting) | Faster (less overhead) |
| Use Case | Good for debugging and simple use cases | Best for efficiency and large data |
std::ofstream, std::ifstream) along with overloaded stream operators (<< and >>) for text-based serialization and deserialization.Open this section to load past papers