Unit 4-2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

1

UNIT -4 OOPS 2022

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:

Assume you have a class `MyClass`:


#include <iostream>
#include <fstream>

class MyClass {
public:
int data;

MyClass() : data(0) {}

MyClass(int value) : data(value) {}

void display() const {


cout << "Data: " << data << endl;
}
};

### Storing Objects in a File (Serialization):


int main() {
const char* filename = "objects.dat";
const int arraySize = 5;

// Create an array of MyClass objects


MyClass objects[arraySize] = {MyClass(1), MyClass(2), MyClass(3), MyClass(4), MyClass(5)};

// Open the file for writing in binary mode


ofstream outFile(filename, ios::binary | ios::out);

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.

### Retrieving Objects from a File (Deserialization):


int main() {
const char* filename = "objects.dat";
const int arraySize = 5;

// Create an array to hold the loaded objects


MyClass loadedObjects[arraySize];

// Open the file for reading in binary mode


ifstream inFile(filename, ios::binary | ios::in);

if (inFile.is_open()) {
// Read the array of objects from the file
inFile.read(reinterpret_cast<char*>(&loadedObjects), sizeof(loadedObjects));
inFile.close();

// Display the loaded objects


for (int i = 0; i < arraySize; ++i) {
loadedObjects[i].display();
}
} else {
cerr << "Error opening file for reading." << endl;
return 1;
}

return 0;
}

Q. NO.7(b), 2022) How to overload template functions? Explain .


A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic
functions and thus provides support for generic programming. Generic programming is a technique where
generic types are used as parameters in algorithms so that they can work for a variety of data types.

Templates can be represented in two ways:


o Function templates
o Class templates

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

Let's understand this through a simple example:


#include <iostream>
using namespace std;
3

template<class X> void fun(X a)


{
cout << "Value of a is : " <<a<< endl;
}
template<class X,class Y> void fun(X b ,Y c)
{
cout << "Value of b is : " <<b<< endl;
cout << "Value of c is : " <<c<< endl;
}
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.8(a), 2022) What is Exception ? How to catch multiple exceptions ?


Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at
run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and
handled by the program.

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.

Using Multiple catch Blocks:


#include <iostream>
int main() {
try {
// Code that might throw exceptions
throw 42; // Example exception

} catch (int i) {
cerr << "Caught an integer exception: " << i << endl;

} catch (double d) {
cerr << "Caught a double exception: " << d << endl;

} catch (const char* msg) {


cerr << "Caught a char* exception: " << msg << endl;
4

} 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};

// Accessing elements within bounds


for (int i = 0; i <= 5; ++i) {
if (i < 5) {
cout << "Element at index " << i << ": " << arr[i] << endl;
} else {
// Attempting to access an element out of bounds
throw out_of_range("Array index out of bounds");
}
}
} catch (const out_of_range& e) {
cerr << "Exception caught: " << e.what() << endl;
}

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.

UNIT -4 OOPS 2021

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

Syntax of Function Template


template < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}

Where Ttype: It is a placeholder name for a data type used by the function.

Example :

Let's see a simple example of a function template:

#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

Overloading a Function Template


We can overload the generic function means that the overloaded template functions can differ in the parameter
list.

Let's understand this through a simple example:


#include <iostream>
using namespace std;
template<class X> void fun(X a)
{
cout << "Value of a is : " <<a<< endl;
}
template<class X,class Y> void fun(X b ,Y c)
{
cout << "Value of b is : " <<b<< endl;
cout << "Value of c is : " <<c<< endl;
6

}
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.

Let's see a simple example:


#include <iostream>
using namespace std;
template<class T>
class A
{
public:
T num1 = 5;
T num2 = 6;
void add()
{
cout << "Addition of num1 and num2 : " << num1+num2<< endl;
}

};
7

int main()
{
A<int> d;
d.add();
return 0;
}

Output:

Addition of num1 and num2 : 11

CLASS TEMPLATE WITH MULTIPLE PARAMETERS


We can use more than one generic data type in a class template, and each generic data type is separated by the
comma.

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:

Values of a and b are : 5,6.5


8

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.

template<class T, int size>


class array
{
T arr[size]; // automatic array initialization.
};

Let's see a simple example of nontype template arguments.


#include <iostream>
using namespace std;
template<class T, int size>
class A
{
public:
T arr[size];
void insert()
{
int i =1;
for (int j=0;j<size;j++)
{
arr[j] = i;
i++;
}
}

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?

User Defined Exception


In C++, you can define your own exceptions by creating a new class that inherits from the standard
exception class or one of its derived classes. Here's an example of how you can create a user-defined
exception in C++:
Example :
#include <iostream>
using namespace std;

class demo1 {
};

class demo2 : public demo1 {


};

int main()
{
for (int i = 1; i <= 2; i++) {
try {
if (i == 1)
throw demo1();

else if (i == 2)
throw demo2();
}

catch (demo1 d1) {


cout << "Caught exception of demo1 class \n";
}
catch (demo2 d2) {
cout << "Caught exception of demo2 class \n";
}
}
}
Output:

Caught exception of demo1 class


Caught exception of demo1 class

scenario where we require user defined exceptions


1. **Domain-Specific Errors:**
- **Scenario:** You are developing a library or application that deals with a specific domain, and there
are unique error conditions or constraints within that domain.
- **Example:** In a financial application, you might want to create a custom exception for handling
specific errors related to financial calculations or transactions.

2. **Custom Error Information:**


10

- **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.

4. **Encapsulation of Error Logic:**


- **Scenario:** You want to encapsulate the error-handling logic within specific parts of your codebase,
providing a more modular and maintainable structure.
- **Example:** When designing a complex system, you might create custom exceptions for each module,
allowing each module to handle its own errors and failures without exposing unnecessary details to other
parts of the system.

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.

6. **Consistent Exception Hierarchy:**


- **Scenario:** You want to maintain a consistent exception hierarchy that aligns with your application's
design.
- **Example:** In an application with a clear class hierarchy, you might create custom exceptions for
each base class, providing a more structured and organized approach to handling errors.

Q. NO.8(b), 2021) Draw a comparison between :


a) Error and Exception
b) Exceptions and Inheritance

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

Aspect Exceptions Inheritance


Purpose Handling runtime errors and Establishing relationships between classes,
abnormal conditions. promoting code reuse, and supporting
polymorphism.
Triggering Events Occurs during the runtime when an Defined at compile-time when a new class is
error is encountered. created.
Syntax Utilizes try-catch blocks for Utilizes keywords like class, struct, and
exception handling. interface for defining relationships and
structures.
Control Flow Alters the normal flow of the Defines relationships between classes for code
program when an exception is organization and reuse.
thrown.
Handling Requires explicit handling using Allows derived classes to inherit and extend
Mechanism try-catch blocks or propagation to the behavior of base classes.
higher levels.
Types Can be standard (e.g., exception) Involves base classes and derived classes in a
or user-defined. hierarchy.
Implementation Implemented using the try, throw, Implemented using keywords like class,
and catch keywords. public, protected, and private.
Runtime Effect Can lead to program termination if Has no direct runtime effect; its impact is seen
not handled properly. during program execution based on the
structure of the inheritance hierarchy.

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).

REMAINING PARTS OF SALLYBUS :

TEXT STREAM AND BINARY STREAM :


A logical interface to a file is known as a stream. A stream is a flow of data from input and output devices to
computer and computer to input or output devices. A flow of characters from an input device to a computer is
called an input stream.
12

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.

SEQUENTIAL AND RANDOM ACCESS FILE


Sequential Access File

 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

STREAM INPUT/OUTPUT CLASSES

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>

using namespace std;

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;

cout << "Enter your age:";


cin >> age;
cout << "\nYour age is: " << age;
15

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>

using namespace std;

int main()
{
istringstream str(" Programmer");
string line;
// Ignore all the whitespace in string
// str before the first word.
getline(str >> ws, line);

// you can also write str>>ws


// After printing the output it will automatically
// write a new line in the output stream.
cout << line << endl;

// without flush, the output will be the same.


cout << "only a test" << flush;

// Use of ends Manipulator


16

cout << "\na";

// NULL character will be added in the Output


cout << "b" << ends;
cout << "c" << endl;

return 0;
}
Output:
Programmer
only a test
abc

You might also like