100% found this document useful (1 vote)
10 views

OOPs Unit5 Preeti

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
100% found this document useful (1 vote)
10 views

OOPs Unit5 Preeti

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/ 13

UNIT-5

C++ Exceptions
When executing C++ code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, C++ will normally stop and generate an error message. The
technical term for this is: C++ will throw an exception (throw an error).

C++ try and catch


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:

Example
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}

Example
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
Example:

#include <iostream>
using namespace std;

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

int main () {
int x = 50;
int y = 0;
double z = 0;

try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}

return 0;
}

Because we are raising an exception of type const char*, so while catching this
exception, we have to use const char* in catch block. If we compile and run above code,
this would produce the following result −
Division by zero condition!
Templates:
Templates in C++ is an interesting feature that is used for generic programming and
templates in c++ is defined as a blueprint or formula for creating a generic class or a
function. Simply put, you can create a single function or single class to work with
different data types using templates.

C++ template is also known as generic functions or classes which is a very powerful
feature in C++. A keyword “template” in c++ is used for the template’s syntax and
angled bracket in a parameter (t), which defines the data type variable.

How do templates work in C++?


Templates in c++ works in such a way that it gets expanded at compiler time, just like
macros and allows a function or class to work on different data types without being
rewritten.

Types of Templates in C++


There are two types of templates in C++

• Function template
• Class templates

What is the function template in C++?

A function template in c++ is a single function template that works with multiple data
types simultaneously, but a standard function works only with one set of data types.

C++ Function Template Syntax

1template<class type>ret-type func-name(parameter list)


2{
3//body of the function
4}

Here, type is a placeholder name for a data type used by the function. It is used within
the function definition.

The class keyword is used to specify a generic type in a template declaration.

C++ function template example:

Source Code:

#include<iostream.h>
using namespace std;
template<classX>//can replace 'class" keyword by "typename" keyword
X func( Xa,Xb)
{
return a;
}
int main()
count<<func(15,8),,endl;//func(int,int);
count,,func('p','q'),,endl;//func(char,char);
count<<func(7.5,9.2),,endl;//func(double,double)
return();
}
Output

15

7.5

Defining a Class Member Outside the Class Template

You’ve seen how a member function is defined within a class template. Now, alternatively, it
is also possible for the template member function to be defined independently of the
declaration of its class template.

The compiler will use the template arguments that you used, in this case, to create the class
template when you call a member function of a class template specialization. The following
illustration exemplifies this:

Example:

#include<iostream>
using namespace std;
template<class A> class B {
public:
A operator+(A);
};

template<class A> A B<A>::operator+(A x) {


return x;
};

int main() {
B<char> ob1;
B<int> ob2;
cout<< ob1 +'p' << endl;
cout<< ob2 + 10;
return 0;
}
Output:

10

A definition of the overloaded addition operator is given outside of class A. It is equal


to the statement ob1.operator+(‘p’) rather than ob1+ “p”. “ob2 + 10” is similar to
“ob2.operator+” (10).

Simple Calculator Using Class Templates

We can make a simple Calculator performing the four basic arithmetic operations in
C++ using a class template. The template of the class will consist of two variables
whose values are passed at the time of object creation. The constructor of this class
takes two arguments of generic datatypes. Further, you will see, this Calculator class
template consists of five main functions – show(), addition(), subtraction(),
multiplication(), and division(). The show() function is responsible for calling the rest
of the four generic functions. Moving ahead, we have created two instances from the
template of Calculator class and performed the basic calculations using its class
functions.

Example:

template <class Temp>


class Calculator
{
private:
Temp n1, n2;

public:
Calculator(Temp num1, Temp num2)
{
n1 = num1;
n2 = num2;
}

void show()
{
cout << "Addition is: " << n1 << "+" << n2 << "=" << addition() << endl;
cout << "Subtraction is: " <<n1 << "-" << n2 << "=" << subtraction() <<
endl;
cout << "Product is: " << n1 << "*" << n2 << "=" << multiplication() <<
endl;
cout << "Division is: " << n1 << "/" << n2 << "=" << division() << endl;
}

Temp addition() { return (n1 + n2); }

Temp subtraction() { return n1 - n2; }

Temp multiplication() { return n1 * n2; }

Temp division() { return n1 / n2; }


};

int main()
{
Calculator<int> Calc1(25, 12);
Calculator<float> Calc2(13.6, 5.9);

cout << "Integer results for 25 and 12:" << endl;


Calc1.show();

cout << endl << "Float results for 13.6 and 5.9:" << endl;
Calc2.show();

return 0;
}
Output
C++ Class Templates With Multiple Parameters

It is possible to provide more than one type when generating templates. A class template can
have many generic data types. They are listed in a comma-delimited format as shown in the
following example.

Example:

#include<iostream>
using namespace std;
// Class template with more than one parameter
template<class Temp1, class Temp2>
class Sample
{
Temp1 l;
Temp2 m;
public:
Sample(Temp1 a, Temp2 b)
{
l = a;
m = b;
}
void display()
{
cout << "The inputs are: " <<l << " and " << m << endl;
}
};

// Driver function
int main()
{
// instantiation
Sample <int, char> ob1 (24, 'A');

// instantiation
Sample<int, float> ob2(22.56, 34.9);

//Calling the display function to see the output


ob1.display();
ob2.display();
return 0;
}

Output:

As seen in the above cited example, we can use more than one parameter for a
template in C++. Here, the template Temp takes two parameters, both of the Sample
class type, separated by a comma. Moreover, the constructor of the Sample class takes
two arguments of generic datatype. When we create objects, the types of arguments
are specified in angular brackets (< >). In case of multiple parameters, the datatypes
are also separated by commas. The constructor is called at the time when objects are
created, and template arguments receive values.

What is class template in c++?


The class template in c++ is like function templates. They are known as generic templates.
They define a family of classes in C++.

Syntax of Class Template

template<class Ttype>
class class_name
{
//class body;
}
Here Type is a placeholder type name, which will be specified when a class instantiated.
The Type can be used inside the body of the class.
Class template in c++ example:

Source Code:

#include<iostream.h>
using namespace std;
template <class C>
class A{
private;
C,a,b;
public:
A(Cx,Cy){
a=x;
b=y;
}
void show()
}
count<<"The Addition of"<<a<<"and"<<b<<"is"<<add()<<endl;
}
C add(){
C c=a+b;
return c;
}
};
int main(){
Aaddint(8,6);
Aaddfloat(3.5,2.6);
Aaaddouble(2.156,5.234);
Aaddint.show();
cout<<endl;
adddouble.show();
count<<endl;
return 0;
}

Output

The addition of 8 and 6 is 14

Addition of 3.5 and 2.6 is 6.1

The addition of 2.156 and 5.234 is 7.390

Advantages of Using Templates in C++


• Templates are type-safe.
• They are generally considered as an improvement over macros for these
purposes.
• Templates avoid some common errors found in code that make heavy
use of function-like macros.
• Both templates and macros are expanded at compile time.
• They are a good way of making generalisations for APIs.
Disadvantages of Using Templates in C++
• Many compilers do not support nesting of templates.
• When templates are used, all codes exposed.
• Some compilers have poor support of templates.
• Approx all compilers produce unhelpful, confusing error messages when
errors are detected in the template code.
• It can make it challenging to develop the template.

File Handling:
Files are used to store data in a storage device permanently. File handling provides a
mechanism to store the output of a program in a file and to perform various operations
on it.

A stream is an abstraction that represents a device on which operations of input and


output are performed. A stream can be represented as a source or destination of
characters of indefinite length depending on its usage.

In C++ we have a set of file handling methods. These include ifstream, ofstream, and
fstream. These classes are derived from fstrembase and from the corresponding
iostream class. These classes, designed to manage the disk files, are declared in fstream
and therefore we must include fstream and therefore we must include this file in any
program that uses files.

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.

• ofstream: This Stream class signifies the output file stream and is applied to
create files for writing information to files
• ifstream: This Stream class signifies the input file stream and is applied for
reading information from files
• fstream: This Stream class can be used for both read and write from/to files.

All the above three classes are derived from fstreambase and from the corresponding
iostream class and they are designed specifically to manage disk files.
C++ provides us with the following operations in File Handling:

• Creating a file: open()


• Reading data: read()
• Writing new data: write()
• Closing a file: close()

Moving on with article on File Handling in C++

Opening a File
Generally, the first operation performed on an object of one of these classes is to
associate it to a real file. This procedure is known to open a file.

We can open a file using any one of the following methods:


1. First is bypassing the file name in constructor at the time of object creation.
2. Second is using the open() function.

To open a file use

open() function
Syntax

void open(const char* file_name,ios::openmode mode);


Here, the first argument of the open function defines the name and format of the file
with the address of the file.

The second argument represents the mode in which the file has to be opened. The
following modes are used as per the requirements.

Modes Description
Opens the file to read(default for
In
ifstream)
Opens the file to write(default for
Out
ofstream)
Binary Opens the file in binary mode
Opens the file and appends all the
app
outputs at the end
Opens the file and moves the control to
ate
the end of the file
trunc Removes the data in the existing file
nocreate Opens the file only if it already exists
Opens the file only if it does not already
noreplace
exist
Example

fstream new_file;
new_file.open(“newfile.txt”, ios::out);
In the above example, new_file is an object of type fstream, as we know fstream is a
class so we need to create an object of this class to use its member functions. So we
create new_file object and call open() function. Here we use out mode that allows us to
open the file to write in it.

Default Open Modes :


• ifstream ios::in
• ofstream ios::out
• fstream ios::in | ios::out

We can combine the different modes using or symbol | .

Example

ofstream new_file;

new_file.open(“new_file.txt”, ios::out | ios::app );


Here, input mode and append mode are combined which represents the file is opened
for writing and appending the outputs at the end.

As soon as the program terminates, the memory is erased and frees up the memory
allocated and closes the files which are opened.
But it is better to use the close() function to close the opened files after the use of the
file.

Using a stream insertion operator << we can write information to a file and using stream
extraction operator >> we can easily read information from a file.

Example of opening/creating a file using the open() function

#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file.close(); // Step 4: Closing file
}
return 0;
}
Output:
Explanation
In the above example we first create an object to class fstream and name it ‘new_file’.
Then we apply the open() function on our ‘new_file’ object. We give the name
‘new_file’ to the new file we wish to create and we set the mode to ‘out’ which allows
us to write in our file. We use a ‘if’ statement to find if the file already exists or not if it
does exist then it will going to print “File creation failed” or it will gonna create a new
file and print “New file created”.

Writing to a File
Example:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file<<"Learning File handling"; //Writing to file
new_file.close();
}
return 0;
}

You might also like