ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP2111Object Serialization
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP2111

    Object Oriented Programming

    Progress0 / 23 done
    Topics23
    1Introduction to object oriented design2History and advantages of object oriented design3Introduction to object oriented programming concepts4Classes and objects5Data encapsulation6Constructors and destructors7Access modifiers8Const vs non-const functions9Static data members & functions10Function overloading11Operator overloading12Identification of classes and their relationships13Composition and aggregation14Inheritance15Multiple inheritance16Polymorphism17Abstract classes and interfaces18Generic programming concepts19Function & class templates20Standard template library21Object streams22Data and object serialization using object streams23Exception handling
    8 min read
    Topic 22 of 23
    Topic Study Note Illustration
    22

    Data and object serialization using object streams

    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...

    Data and Object Serialization Using Object Streams in C++

    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.


    1. Object Serialization Process

    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).

    2. Object Serialization with Text Streams

    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.

    Steps for Text-Based Serialization and Deserialization:

    1. Serialization: Write the object's data to a text stream.
    2. Deserialization: Read the data back from the stream and reconstruct the object.

    Example: Serialization and Deserialization using Text Streams

    #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;
    }
    

    Explanation:

    • The Person class has two data members: name (string) and age (int).
    • The insertion operator (<<) writes the data of the Person object to an output stream (ofstream).
    • The extraction operator (>>) reads the data from an input stream (ifstream) to reconstruct the Person object.
    • The 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
    

    3. Object Serialization with Binary Streams

    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.

    Steps for Binary Serialization and Deserialization:

    1. Serialization: Write the object's data as raw binary data to a stream.
    2. Deserialization: Read the binary data back from the stream and reconstruct the object.

    Example: Serialization and Deserialization using Binary Streams

    #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;
    }
    

    Explanation:

    • The writeBinary() method serializes the Person object into a binary format:
      • First, it writes the length of the name string (as a size_t), followed by the string itself.
      • Then, it writes the integer age.
    • The readBinary() method deserializes the object from the binary format:
      • It first reads the length of the name string, then the string itself.
      • Finally, it reads the integer age.

    Binary file contents are not human-readable, as the data is stored in raw binary format.


    4. Comparing Text vs Binary Serialization

    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

    5. Considerations for Serialization

    • Portability: Binary serialization may depend on the system's architecture (e.g., byte order), making it less portable. You should carefully handle differences between systems if sharing data.
    • Backward Compatibility: Changes to the class (e.g., adding/removing data members) may break compatibility with older serialized files.
    • Security: Be cautious when deserializing data, as it can be tampered with and may lead to security vulnerabilities.

    6. Summary

    • Serialization is the process of converting an object's state into a format that can be easily saved to a file or transmitted over a network.
    • Deserialization is the reverse process, where the serialized data is used to recreate the original object.
    • C++ uses object streams (std::ofstream, std::ifstream) along with overloaded stream operators (<< and >>) for text-based serialization and deserialization.
    • Binary serialization is more efficient for large data, but requires careful handling of byte formats.
    • Always consider portability, backward compatibility, and security when working with serialization in C++.
    ← Previous topic 21
    Object streams
    Next topic 23 →
    Exception handling

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    8mremaining
    1.3kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Object Oriented Programming