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
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Object Streams: Data and Object Serialization
    Object Oriented ProgrammingTopic 23 of 24

    Object Streams: Data and Object Serialization

    8 minread
    1,311words
    Intermediatelevel

    Object Streams: Data and Object Serialization in C++

    In C++, object streams refer to the mechanisms that allow the serialization and deserialization of objects to and from various forms of storage, such as files or network streams. Serialization is the process of converting an object's state into a format that can be stored or transmitted, while deserialization refers to the process of reconstructing the object from that format.

    C++ provides mechanisms for data serialization (storing primitive types) and object serialization (storing entire objects). Object serialization and deserialization are useful for saving the state of objects to files or transferring objects over networks.

    Data Serialization: Basic Concept

    Data serialization refers to saving primitive data types or simple data structures (like arrays or lists) to a stream. This can be achieved using I/O streams in C++.

    Example of Data Serialization:

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main() {
        int a = 10;
        double b = 3.14;
        char c = 'X';
    
        // Creating an output file stream to serialize the data into a file
        ofstream outFile("data.txt");
    
        // Serializing primitive data types to the file
        outFile << a << endl;
        outFile << b << endl;
        outFile << c << endl;
    
        outFile.close();  // Close the file
    
        return 0;
    }
    

    Explanation:

    • The values of a, b, and c are written to the file data.txt using ofstream. Each value is written to a new line.
    • The << operator is overloaded in C++ streams to handle the writing of data.

    Object Serialization: Working with Objects

    Object serialization involves converting an entire object (which can contain multiple members, including other objects) into a format that can be stored or transmitted.

    Serialization Process:

    1. Store Object's State: Save the object's data members to a file or a stream.
    2. Deserialize Object's State: Retrieve the data members from the stream and reconstruct the object.

    For serializing objects, we use output file streams (ofstream) for storing data and input file streams (ifstream) for reading the data back.

    Steps to Serialize and Deserialize Objects in C++

    To implement object serialization, we need to:

    1. Create a class with serializable members.
    2. Define functions to serialize (write) and deserialize (read) the object.

    Example: Object Serialization and Deserialization

    1. Class Definition and Member Functions

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    class Person {
    private:
        string name;
        int age;
    
    public:
        // Constructor
        Person(string name = "", int age = 0) : name(name), age(age) {}
    
        // Function to serialize the object (write to file)
        void serialize(ofstream& out) {
            out << name << endl;
            out << age << endl;
        }
    
        // Function to deserialize the object (read from file)
        void deserialize(ifstream& in) {
            getline(in, name);
            in >> age;
            in.ignore();  // Ignore newline character after reading age
        }
    
        // Function to display object data
        void display() const {
            cout << "Name: " << name << ", Age: " << age << endl;
        }
    };
    
    int main() {
        // Create a Person object
        Person p1("Alice", 30);
    
        // Serialize the object to a file
        ofstream outFile("person.dat");
        p1.serialize(outFile);
        outFile.close();
    
        // Deserialize the object from the file
        Person p2;
        ifstream inFile("person.dat");
        p2.deserialize(inFile);
        inFile.close();
    
        // Display the deserialized object data
        p2.display();
    
        return 0;
    }
    

    Explanation:

    1. The Person class has two private data members: name (a string) and age (an integer).
    2. The serialize function writes the name and age to the output file stream.
    3. The deserialize function reads data from the input file stream and reconstructs the object.
    4. In the main() function:
      • A Person object p1 is created and serialized to the file person.dat.
      • A new Person object p2 is created, and its data is deserialized from the file.
      • Finally, the deserialized object p2 is displayed using the display method.

    Output:

    Name: Alice, Age: 30
    

    Object Serialization with Binary Files

    The above example uses text-based serialization, where data is stored as human-readable text. Another method is binary serialization, where objects are stored in a binary format, which can be more compact and efficient.

    Binary Serialization Example:

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    class Person {
    private:
        string name;
        int age;
    
    public:
        // Constructor
        Person(string name = "", int age = 0) : name(name), age(age) {}
    
        // Function to serialize the object in binary format
        void serialize(ofstream& out) {
            size_t nameLength = name.length();
            out.write(reinterpret_cast<char*>(&nameLength), sizeof(nameLength));  // Write the length of the name
            out.write(name.c_str(), name.length());  // Write the name
            out.write(reinterpret_cast<char*>(&age), sizeof(age));  // Write age
        }
    
        // Function to deserialize the object in binary format
        void deserialize(ifstream& in) {
            size_t nameLength;
            in.read(reinterpret_cast<char*>(&nameLength), sizeof(nameLength));  // Read the length of the name
            char* buffer = new char[nameLength + 1];
            in.read(buffer, nameLength);  // Read the name
            buffer[nameLength] = '\0';  // Null-terminate the name string
            name = buffer;
            delete[] buffer;
            in.read(reinterpret_cast<char*>(&age), sizeof(age));  // Read age
        }
    
        // Function to display object data
        void display() const {
            cout << "Name: " << name << ", Age: " << age << endl;
        }
    };
    
    int main() {
        // Create a Person object
        Person p1("Bob", 25);
    
        // Serialize the object to a binary file
        ofstream outFile("person.dat", ios::binary);
        p1.serialize(outFile);
        outFile.close();
    
        // Deserialize the object from the binary file
        Person p2;
        ifstream inFile("person.dat", ios::binary);
        p2.deserialize(inFile);
        inFile.close();
    
        // Display the deserialized object data
        p2.display();
    
        return 0;
    }
    

    Explanation of Binary Serialization:

    1. In the serialize method, we first write the length of the name (so that we can correctly read it during deserialization), followed by the name itself and then the age.
    2. The deserialize method reads the length of the name, allocates a buffer to hold the name string, and then reads the name and age into the object.
    3. We open the file in binary mode by using ios::binary in both the input and output file streams.

    Binary File Format:

    • The file will contain the length of the name (in bytes), followed by the characters of the name and the age, all in binary format.

    Advantages and Disadvantages of Serialization

    Advantages:

    1. Persistence: Serialization allows you to save the state of objects to files or databases, enabling persistence across sessions.
    2. Interoperability: Objects can be transmitted over a network or saved to a file, making it possible to share data between different systems or platforms.
    3. Compact Storage: Binary serialization usually results in more compact data storage compared to text-based formats.

    Disadvantages:

    1. Complexity: For complex objects, managing the serialization and deserialization code can be cumbersome, especially when dealing with deep object hierarchies.
    2. Portability: Binary formats are platform-specific, and deserialization might fail if the program is run on a different architecture (due to issues like byte-ordering).
    3. Performance: Serialization and deserialization processes, especially with large objects or complex data structures, can be computationally expensive.

    Conclusion

    Serialization in C++ is a powerful mechanism for saving and loading objects to and from storage or across network boundaries. By converting an object's state into a format that can be stored or transmitted, you can make objects persistent and shareable. Whether using text-based or binary serialization, it is important to handle the process carefully to ensure data integrity and portability across different systems.

    Previous topic 22
    Standard Template Library
    Next topic 24
    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,311
      Code examples0
      DifficultyIntermediate