Unit 4-2
Unit 4-2
Unit 4-2
Q. NO.7(a), 2022) Explain, how array of class objects can be stored and retrieved from a file ?
To store and retrieve an array of class objects from a file in C++, you need to perform serialization and
deserialization. Serialization is the process of converting the object's state into a format that can be easily
stored, typically in a file. Deserialization is the reverse process, where you read the data from the file and
reconstruct the objects. Here's a step-by-step guide:
class MyClass {
public:
int data;
MyClass() : data(0) {}
if (outFile.is_open()) {
// Write the array of objects to the file
outFile.write(reinterpret_cast<char*>(&objects), sizeof(objects));
outFile.close();
cout << "Objects have been serialized and stored in the file." << endl;
} else {
cerr << "Error opening file for writing." << endl;
return 1;
}
return 0;
}
2
In this code snippet, the objects are serialized and stored in a file named "objects.dat" using ` ofstream`. The
`reinterpret_cast` is used to treat the array of objects as a raw block of memory, allowing it to be written to
the file.
if (inFile.is_open()) {
// Read the array of objects from the file
inFile.read(reinterpret_cast<char*>(&loadedObjects), sizeof(loadedObjects));
inFile.close();
return 0;
}
To overload a template function in C++, you can use either a non-template function or another function
template. Here is an example of function template overloading in C++:
Overloading a Function Template
Output:
Value of a is : 10
Value of b is : 20
Value of c is : 30.5
Exception handling in C++ consist of three keywords: try, throw and catch:
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The throw keyword throws an exception when a problem is detected, which lets us create a custom error.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The try and catch keywords come in pairs:
To catch multiple exceptions in C++, you can use multiple catch blocks or a single catch block with
multiple exception types.
} catch (int i) {
cerr << "Caught an integer exception: " << i << endl;
} catch (double d) {
cerr << "Caught a double exception: " << d << endl;
} catch (...) {
cerr << "Caught an unknown exception" << endl;
}
return 0;
}
Q. NO.8(b), 2022) Write a program for catching array out of bound exception.
#include <iostream>
#include <stdexcept>
int main() {
try {
int arr[5] = {1, 2, 3, 4, 5};
return 0;
}
In this example:
We have an array arr of size 5.
In the loop, we access elements within bounds (up to index 4) using arr[i].
When i becomes 5 (out of bounds), we throw a out_of_range exception.
The exception is caught in the catch block, and an error message is printed.
Q. NO.7(a), 2021) } What are function template? With an example, show how to
overload template function.
Function Templates:
We can define a template for a function. For example, if we have an add() function, we can create versions of
the add function for adding the int, float or double type values.
5
Where Ttype: It is a placeholder name for a data type used by the function.
Example :
#include <iostream>
using namespace std;
template<class T> T add(T &a,T &b)
{
T result = a+b;
return result;
}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<'\n';
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
Output:
Addition of i and j is :5
Addition of m and n is :3.5
}
int main()
{
fun(10);
fun(20,30.5);
return 0;
}
Output:
Value of a is : 10
Value of b is : 20
Value of c is : 30.5
Q. NO.7(b), 2021) Write a detailed note on class template and non-type parameters.
Class Templates:
A class template is a blueprint for creating a family of classes. It allows you to define a generic class without
specifying the actual type of data it will work with. The template is parameterized by one or more types, and
you can use these parameters throughout the class definition.
Syntax
template<class Ttype>
class class_name
{
. ……….
………..
}
Now, we create an instance of a class
class_name<type> ob;
where class_name: It is the name of the class.
};
7
int main()
{
A<int> d;
d.add();
return 0;
}
Output:
Syntax
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}
#include <iostream>
using namespace std;
template<class T1, class T2>
class A
{
T1 a;
T2 b;
public:
A(T1 x,T2 y)
{
a = x;
b = y;
}
void display()
{
cout << "Values of a and b are : " << a<<" ,"<<b<< endl;
}
};
int main()
{
A<int,float> d(5,6.5);
d.display();
return 0;
}
Output:
Non-type Parameters:
Non-type parameters allow you to pass values, which are not types, as template parameters. These values
must be constant expressions known at compile time. Non-type parameters can be integers, enumerations,
pointers, or references.
void display()
{
for(int i=0;i<size;i++)
{
cout << arr[i] << " ";
}
}
};
int main()
{
A<int,10> t1;
t1.insert();
t1.display();
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
9
Q. NO.8(a), 2021)What is a user defined exception? Write down the scenario where we
require user defined exceptions?
class demo1 {
};
int main()
{
for (int i = 1; i <= 2; i++) {
try {
if (i == 1)
throw demo1();
else if (i == 2)
throw demo2();
}
- **Scenario:** You need to provide additional information about the error beyond what is available with
standard exceptions.
- **Example:** A custom exception might include more detailed context information, such as specific
values or states that led to the error, helping in better diagnosis during debugging.
3. **Application-Specific Constraints:**
- **Scenario:** Your application has specific constraints or requirements that are not covered by the
standard exceptions.
- **Example:** In a game development scenario, you might define custom exceptions for handling errors
related to game-specific rules or constraints, such as invalid moves or actions.
5. **Better Expressiveness:**
- **Scenario:** You want to enhance the expressiveness of your code by using more descriptive exception
types.
- **Example:** Instead of using a generic exception, you might create specialized exceptions like
`FileNotFoundError`, `DatabaseConnectionError`, or `InvalidInputError` to communicate the nature of the
error more clearly.
Errors Exceptions
Recovering from Error is not possible. We can recover from exceptions by either using try-catch
block or throwing exceptions back to the caller.
All errors in java are unchecked type. Exceptions include both checked as well as unchecked
type.
Errors are mostly caused by the Program itself is responsible for causing exceptions.
environment in which program is
running.
Errors can occur at compile time. Unchecked exceptions occurs at runtime whereas checked
exceptions occurs at comile time
They are defined in java.lang.Error They are defined in java.lang.Exception package
package.
11
Usage Primarily used for error handling Primarily used for creating and organizing
and recovery. class hierarchies.
Exception May include specific exception Involves specifying base classes and their
Specification types in the catch block or catch any relationships in the class definition.
type using ... (ellipsis).
A sequence of the flow of characters from the computer to the output device is called an output stream. A
stream is associated with a file using an open operation. By using a close operation, a stream is disassociated
from the file.
Types of Stream
There are two types of streams in the C language
Text Stream
It is a collection of sequences of characters. Character translation may be done in a text stream, but in a binary
stream, translation cannot be done.
For example, a new line may be converted to a carriage return/line feed pair It means that there may not be a
one-to-one relationship between the written characters and the characters in an external device.
Binary Stream
It is a sequence of bytes. In the binary stream, translation is not done. It exists with one-to-one correspondence
with external devices. The number of bytes can be written or read as the same as the number of bytes on the
external device. However, an Implementation-defined number of bytes may be appended to a binary stream.
Difference between Text and Binary Stream
The difference between the text stream and the binary stream is as follows:
Text Stream Binary Stream
It is a sequence of characters. It is a sequence of bytes.
It does not have a one-to-one relationship with external It has a one-to-one relationship with external
devices. devices
A certain character translation may occur in the text No translation occurs in the binary stream.
stream
It is less efficient than a binary stream. It is more efficient than a text stream.
It can be used only for text data. It can be used for different types of data.
This types of file create problems with portability. This type of file can easily be portable.
If any error occurs in the text file, it can be easily found Errors in the binary files cannot be easily
and eliminated. recognized, they corrupt the binary file.
In the text file, there are special characters at the end of a In Binary files, there are special characters to
file that signals the EOF to the program. signal EOF.
In a sequential access file, data is stored in a continuous sequence one after the other.
Each record in the file is written after the previous one, and there is no direct way to access a specific
record without traversing through the preceding records.
Reading and writing data in a sequential access file follows a strict order: you read or write data from
the beginning of the file to the end, or vice versa.
13
Once you read or write a particular part of the file, you need to move the file pointer to the next
position to read or write the next piece of data. This is the default file access method in most
programming languages.
It is best suited for tasks where data is processed in the order it is stored, like logs, simple databases,
or large data sets that need to be processed sequentially.
Random Access File
In a random access file, data is stored in a way that allows direct access to any record in the file
without having to read through the preceding records.
Each record has a unique identifier (often called a record number or a key) that helps locate and
access it directly.
Random access files provide faster access to specific records, but they may require addition al
overhead to manage the record numbers or keys.
Random access files are more suitable for applications where you need quick access to specific data,
such as databases with indexed records.
You can directly move the file pointer to a particular location i n the file and read or write data from
that point.
This method is useful when you need to access specific records or data in a non -sequential manner.
Parameter Sequential Access Random Access
Access Speed Sequential access files are slower Random access files, on the other hand,
compared to random access files since allow direct access to specific records,
accessing a specific record requires reading resulting in faster access times.
through all the previous records in the file
Access Method Sequential access files allow access to Random access files allow direct access to
records in a sequential manner specific records using an index, record
number, or key.
Record Sequential access files store records in a Random access files do not have any
Ordering specific order, usually the order in which specific order of storing records.
they were added to the file.
Insertion of Inserting a new record in a sequential Random access files may require
New Record access file is relatively easy since new relocating other records to maintain the
records are added to the end of the file. order so insertion becomes hard as
compared to sequential access.
Memory Sequential access files require less memory Random access files require more memory
Requirements than random access files since they do not because of indexing information
need to store any indexing information.
Search Search flexibility is limited in sequential Random access files offer higher search
Flexibility access file. flexibility than sequential access files
since they allow for direct access to
specific records based on various search
criteria
Record Sizes In sequential access files, record sizes are Random access files, record sizes can be
usually uniform variable
14
File Sequential access files are typically Random access files are typically indexed.
Organization organized in a linear fashion
Examples Text files, Logs Database, Spreadsheet
In C++ stream refers to the stream of characters that are transferred between the program thread and i/o.
Stream classes in C++ are used to input and output operations on files and io devices. These classes have
specific features and to handle input and output of the program.
The iostream.h library holds all the stream classes in the C++ programming language.
1. iostream: iostream stands for standard input-output stream. This header file contains definitions of
objects like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators. The methods declared in these files are used
for manipulating streams. This file contains definitions of setw, setprecision, etc.
3. fstream: This header file mainly describes the file stream. This header file is used to handle the data
being read from a file as input or data being written into the file as output.
Standard output stream (cout): Usually the standard output device is the display screen. The
C++ cout statement is the instance of the ostream class. It is used to produce output on the standard output
device which is usually the display screen.
#include <iostream>
int main()
{
char sample[] = "GeeksforGeeks";
cout << sample << " - A computer science portal for geeks";
return 0;
}
standard input stream (cin): Usually the input device in a computer is the keyboard. C++ cin statement
is the instance of the class istream and is used to read input from the standard input device which is
usually a keyboard.
#include <iostream>
using namespace std;
int main()
{
int age;
return 0;
}
STREAM MANIPULATORS
Manipulators are helping functions that can modify the input/output stream. It does not mean that we
change the value of a variable, it only modifies the I/O stream using insertion (<<) and extraction (>>)
operators.
Manipulators are special functions that can be included in the I/O statement to alter the format
parameters of a stream.
Manipulators are operators that are used to format the data display.
To access manipulators, the file iomanip.h should be included in the program.
For example, if we want to print the hexadecimal value of 100 then we can print it as:
cout<<setbase(16)<<100
Types of Manipulators There are various types of manipulators:
1. Manipulators without arguments: The most important manipulators defined by the IOStream
library are provided below.
endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes
(i.e. it forces all the output written on the screen or in the file) the output stream.
ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.
ends: It is also defined in ostream and it inserts a null character into the output stream. It typically
works with ostrstream, when the associated output buffer needs to be null-terminated to be
processed as a C string.
flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output
written on the screen or in the file. Without flush, the output would be the same, but may not
appear in real-time. Examples:
#include <iostream>
#include <istream>
#include <sstream>
#include <string>
int main()
{
istringstream str(" Programmer");
string line;
// Ignore all the whitespace in string
// str before the first word.
getline(str >> ws, line);
return 0;
}
Output:
Programmer
only a test
abc