lect02_unit04_PersistentObjects
lect02_unit04_PersistentObjects
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.
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:
class Person {
private:
string name;
int age;
public:
Person() : name(""), age(0) {}
Person(const string& name, int age) : name(name), age(age) {}
int main() {
Person p1("Alice", 25);
p1.serializeText("person.txt");
Person p2;
p2.deserializeText("person.txt");
p2.display();
return 0;
}
Example 2:
#include <iostream>
#include <fstream>
#include <string>
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;
}
outFile.close();
}
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();
return 0;
}
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