0% found this document useful (0 votes)
3 views

lect02_unit04_PersistentObjects

Uploaded by

fosefan745
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

lect02_unit04_PersistentObjects

Uploaded by

fosefan745
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Paper Code: CIC-211

Subject: Object-Oriented Programming Using C++

Unit04, Lecture 02:

Topics Covered: Persistant Objects (Object Serialization & De-


Serialization),

1. Introduction to Persistent Objects


 A persistent object is an object whose state outlives the execution of the program that
created it. In simpler terms, it refers to objects that retain their state even after the program
has terminated, allowing the object to be reloaded or reused in subsequent executions of
the program.
 This is generally achieved by saving the object’s state to a file or database and later
retrieving it.
 In C++, persistence is not built into the language by default. However, persistence can
be achieved by serializing the object (converting it into a storable format) and writing
it to a file (or database).
 Later, the object can be deserialized (read from the file and reconstructed back into
memory).

2. Serialization and Deserialization


To make an object persistent, we use two key processes:

 Serialization: Converting an object into a storable format (e.g., binary or text).


 Deserialization: Reconstructing an object from its serialized format.

3. Object Serialization in C++

To serialize an object, we usually write its data members to a file. C++ provides multiple ways to
handle file I/O, such as using the fstream library.

Syntax for File I/O-


#include <fstream>
//Opening a file for output (serialization):
std::ofstream outFile("myFile.dat", std::ios::binary);
//Opening a file for input (deserialization):
std::ifstream inFile("fmyFile.dat", std::ios::binary);
4. Persistent Objects with Text Serialization

Apart from binary serialization, text-based serialization is also possible. Instead of using binary
formats, you can serialize an object to a text file (like JSON or XML). Here’s a simpler approach
using text files:

Example 1: Serializing and Deserializing with Text Files


#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Person {
private:
string name;
int age;

public:
Person() : name(""), age(0) {}
Person(const string& name, int age) : name(name), age(age) {}

void display() const {


cout << "Name: " << name << ", Age: " << age << endl;
}

// Serialize to text file


void serializeText(const string& filename) const {
ofstream outFile(filename);
if (!outFile) {
cerr << "File could not be opened!" << endl;
return;
}

outFile << name << endl; // Save name as text


outFile << age << endl; // Save age as text
outFile.close();
}

// Deserialize from text file


void deserializeText(const string& filename) {
ifstream inFile(filename);
if (!inFile) {
cerr << "File could not be opened!" << endl;
return;
}

getline(inFile, name); // Read name from text


inFile >> age; // Read age from text
inFile.close();
}
};

int main() {
Person p1("Alice", 25);
p1.serializeText("person.txt");

Person p2;
p2.deserializeText("person.txt");
p2.display();

return 0;
}

5. Using Binary File

Example 2:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Person {
private:
string name;
int age;

public:
Person() : name(""), age(0) {} // Default constructor
Person(const string& name, int age) : name(name), age(age) {}
// Display the details of the person
void display() const {
cout << "Name: " << name << ", Age: " << age << endl;
}

// Function to serialize (save) the object to a binary file


void serialize(const string& filename) const {
ofstream outFile(filename, ios::binary);
if (!outFile) {
cerr << "File could not be opened!" << endl;
return;
}

size_t nameLen = name.size();


outFile.write(reinterpret_cast<const char*>(&nameLen), sizeof(nameLen));
// Save name length
outFile.write(name.c_str(), nameLen); // Save name
outFile.write(reinterpret_cast<const char*>(&age), sizeof(age)); // Save
age

outFile.close();
}

// Function to deserialize (load) the object from a binary file


void deserialize(const string& filename) {
ifstream inFile(filename, ios::binary);
if (!inFile) {
cerr << "File could not be opened!" << endl;
return;
}

size_t nameLen;
inFile.read(reinterpret_cast<char*>(&nameLen), sizeof(nameLen)); //
Load name length
char* nameBuffer = new char[nameLen + 1];
inFile.read(nameBuffer, nameLen); // Load name
nameBuffer[nameLen] = '\0';
name = nameBuffer;
delete[] nameBuffer;
inFile.read(reinterpret_cast<char*>(&age), sizeof(age)); // Load age

inFile.close();
}
};

int main() {
// Create a Person object
Person p1("John Doe", 30);
cout << "Original Object:" << endl;
p1.display();

// Serialize the object


p1.serialize("person.dat");

// Deserialize into another object


Person p2;
p2.deserialize("person.dat");

cout << "\nDeserialized Object:" << endl;


p2.display();

return 0;
}

Advantages and Disadvantages

Advantages:

Object persistence: Allows objects to be stored and reused later, even across program executions.

Efficiency: Useful for large, complex applications that need to save and load data between sessions.

Data sharing: Allows sharing data between different programs by storing it in files or databases.

Disadvantages:

Overhead: Serialization and deserialization introduce overhead in terms of processing time and
memory usage.
Versioning issues: When the structure of an object changes (e.g., a new data member is added),
deserializing older versions can lead to compatibility issues.

Security: If sensitive data is stored in files, it can be accessed and exploited unless properly protected
(e.g., encryption).

References:-

Online

1. Tutorialspoint OOP Tutorial: Comprehensive tutorials on OOP concepts with examples. Link
2. GeeksforGeeks OOP Concepts: Articles and examples on OOP principles and applications. Link
3. https://canvas.rku.ac.in/courses/3333/pages/specifying-a-class

Book

1. "Object-Oriented Analysis and Design with Applications" by Grady Booch: Classic book covering
fundamental OOP concepts and real-world examples.
2. "Object-Oriented Programming in C++" by Robert Lafore: Detailed guide to OOP in C++, explaining
concepts with a practical example

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy