ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    COMP2111
    Progress0 / 23 topics
    Topics
    1. Introduction to object oriented design2. History and advantages of object oriented design3. Introduction to object oriented programming concepts4. Classes and objects5. Data encapsulation6. Constructors and destructors7. Access modifiers8. Const vs non-const functions9. Static data members & functions10. Function overloading11. Operator overloading12. Identification of classes and their relationships13. Composition and aggregation14. Inheritance15. Multiple inheritance16. Polymorphism17. Abstract classes and interfaces18. Generic programming concepts19. Function & class templates20. Standard template library21. Object streams22. Data and object serialization using object streams23. Exception handling
    COMP2111›Data and object serialization using object streams
    Object Oriented ProgrammingTopic 22 of 23

    Data and object serialization using object streams

    8 minread
    1,288words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,288
      Code examples0
      DifficultyIntermediate