Presentations PPT Unit-8 27042019041949AM

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

2140705

Object Oriented
Programming with C++

Unit-8
Templates,
Exceptions and STL
Prof. Rupesh G. Vaishnav
9428037452
rupesh.vaishnav@darshan.ac.in
Templates, Exceptions and STL Weightage: 15%

 What is template?
 Function templates and class templates
 Introduction to exception
 Try-catch, throw
I like C++ so much
 Multiple catch


Catch all
I like
Rethrowing exception
Rupesh sir
 Implementing user defined exceptions
 Overview and use of Standard Template Library(STL)

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 2
Exception

1/0
Introduction to Exception
int main()
{
int a,b,c;
cout<<"Enter value a=";
cin>>a;
I like C++ so much
cout<<"Enter value b=";
cin>>b;
c=a/b;
cout<<"answer="<<c;
I like Rupesh sir
}
Output: Output:
Enter value a=5 Enter value a=5
Enter value b=2 Enter value b=0
answer=2 Abnormal Termination occur
Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 4
Introduction to Exception(Cont…)

 Runtime errors are termed as exception.


I like C++ so much
 Exception handling is the process to manage the runtime errors

I like Rupesh sir


by converting the abnormal termination of a program to normal
termination of a program.

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 5
try, throw and catch

try

I like C++ so much


I like Rupesh sir
throw catch

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 6
try, throw and catch
 C++ exception handling mechanism is built upon three keywords
try, throw and catch.
try
try block {
Detects and throws an .....

I like C++ so much


exception throw exception; //this block
detects and throws an exception
}
Exception
Object
I like Rupesh sir
catch(type arg)
catch block {
Catches and handles .....
... //exception handling block
the exception }
.....

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 7
int main()
{ try, throw and catch example
int a,b,c;
cout<<"Enter two values=";
cin>>a>>b;
try Output:
{ Enter value a=5
if(b!=0) Enter value b=0
c=a/b; Exception caught: Divide by zero
cout<<"answer="<<c;
else
throw(b);
}
catch(int x)
{
cout<<"Exception caught: Divide by zero\
n";
}
}
void test(int x){
try Multiple catch example
{
if(x==1) int main()
throw x; {
else if(x==0) test(1);
throw 'x'; test(0);
else if(x==-1) test(-1);
throw 5.14; }
}
catch(int i){
cout<<"\nCaught an integer";
}
catch(char ch){
cout<<"\nCaught a character"; Output:
} Caught an integer
catch(double i){ Caught a character
cout<<"\nCaught a double"; Caught a double
}
}
Catch all Exception
Catch all exception
 In some situations, we may not predict all possible types of
exceptions and therefore may not be able to design independent
catch handlers to catch them.

Syntax:
catch(...) I like C++ so much
{
I like Rupesh sir
//statements for processing all exceptions
}

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 11
Catch all exception example
#include<iostream> int main()
using namespace std; {
void test(int x) test(-1);
{ test(0);
try test(1);
{
I like C++ so much
if(x==0) throw x;
}

if(x==-1) throw 'a';

}
I like Rupesh sir
if(x==1) throw 5.15;

catch(...)
{ Output:
cout<<"Caught an exception\n"; Caught an exception
} Caught an exception
} Caught an exception

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 12
Re-Throwing exception

 An exception is thrown from the catch block is known as the re-


throwing exception. I like C++ so much
 It can be simply invoked by throw without arguments.
I like Rupesh sir
 Rethrown exception will be caught by newly defined catch
statement.

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 13
void divide(double x, double y){
try
{
int main()
if(y==0)
{
throw y;
try
else
{
cout<<"Division="<<x/y;
divide(10.5,2.0);
}
divide(20.0,0.0);
catch(double)
}
{
catch(double)
cout<<"Exception inside
{
function\n";
cout<<"Exception inside
throw;
main function";
}
}
}
}
Output:
Division=5.25
Exception inside function
Exception inside main function
Exceptions thrown from
functions
#include <iostream>
using namespace std;
void test(int x)
{
cout<<"Inside function:"<<x<<endl;
if(x) throw x;
}
int main()
{
cout<<"Start"<<endl;
try
{
test(0);
test(1);
test(2);
}
catch(int x)
{
cout<<"Caught an int exception:"<< x<<endl;
}

}
User defined Exception

 There maybe situations where you want to generate some user


I like C++ so much
specific exceptions which are not pre-defined in C++.

exceptions byI inheriting


like Rupesh sir in C++.
 In such cases C++ provided the mechanism to create our own
the exception class

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 17
#include <iostream> User defined Exception
#include <exception>
class myexception: public exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
} myex;
int main (){
try
{
throw myex;
}
catch (exception& e)
{
cout << e.what() << '\n';
}
}
User defined Exception(Cont…)
double myfunction (char arg) throw (int);
 This declares a function called myfunction, which takes one
argument of type char and returns a value of type double.
 If this function throws an exception of some type other than int,

I like C++ so much


the function calls std::unexpected instead of looking for a handler
or calling std::terminate.

I like Rupesh sir


 If this throw specifier is left empty with no type, this means that
std::unexpected is called for any exception.
 Functions with no throw specifier (regular functions) never call
std::unexpected, but follow the normal path of looking for their
exception handler.
int myfunction (int param) throw(); //all exceptions call unexpected
int myfunction (int param); //normal exception handling

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 19
Template
Need of Templates
int add(int x, int y) float add(float x, float y)
{ {
return x+y; return x+y;
} }

I like C++ so much


char add(char x,char y) double add(double x, double y)
{ {

I like Rupesh sir


return x+y; return x+y;
} }

We need a single function that will work for int, float, double etc…

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 21
Templates
 Templates concept enables us to define generic classes and
functions.
 This allows a function or class to work on many different data
types without being rewritten for each one.
I like C++ so much
I like Rupesh
Templatessir

Function Class
Template Template
Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 22
Function Template
Syntax:
template<class Ttype>

Keyword Placeholder name


I likeSpecifies
C++genericso much for a datatype

I like Rupesh sir


type in a Template

template<typename Ttype>

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 23
Templates
 C++ templates are a powerful mechanism for code reuse, as they
enable the programmer to write code that behaves the same for
any data type.


I like C++ so much
 By template we can define generic classes and functions.
In simple terms, you can create a single function or a class to work
with differentI data
liketypesRupesh sir
using templates.
 It can be considered as a kind of macro. When an object of a
specific type is defined for actual use, the template definition for
that class is substituted with the required data type.

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 24
Function Template
 Suppose you write a function printData:
void printData(int value){
cout<<"The value is "<<value;
}
 Now if you want to print double values or string values, then you
I like C++ so much
have to overload the function:
void printData(float value){

}
I like Rupesh sir
cout<<"The value is "<<value;

void printData(char *value) {


cout<<"The value is "<<*value;
}
 To perform same operation with different data type, we have to
write same code multiple time.

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 25
Function Template (Cont…)
 C++ provides templates to reduce this type of duplication of code.
template<typename T>
void printData(T value){
cout<<"The value is "<<value;
}

I like C++ so much


 We can now use printData for any data type. Here T is a
template parameter that identifies a type.
I like Rupesh sir
 Then, anywhere in the function where T appears, it is replaced
with whatever type the function is instantiated.
int i=3;
float d=4.75;
char *s="hello";
printData(i); // T is int
printData(d); // T is float
printData(s); // T is string
Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 26
#include <iostream>  T is a template argument that
using namespace std;
accepts different data types
template <typename T>
 typename is a keyword
T Large(T n1, T n2)
 You can also use
{
return (n1 > n2) ? n1 : n2; keyword class instead of
} typename
int main(){
int i1, i2; float f1, f2; char c1, c2;
cout << "Enter two integers:\n";
cin >> i1 >> i2;
cout << Large(i1, i2) <<" is larger." << endl;
cout << "\nEnter two floating-point numbers:\n";
cin >> f1 >> f2;
cout << Large(f1, f2) <<" is larger." << endl;
cout << "\nEnter two characters:\n";
cin >> c1 >> c2;
cout << Large(c1, c2) << " has larger ASCII value.";
}
Class Template
 Sometimes, you need a class implementation that is same for all
classes, only the data types used are different.
 Normally, you would need to create a different class for each data
type OR create different member variables and functions within a
single class.
I like C++ so much
I like Rupesh sir

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 28
Class Template
Syntax:
template<class Ttype>

Keyword Placeholder name


I likeSpecifies
C++genericso much for a datatype

I like Rupesh sir


type in a Template

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 29
Object of template class
The object of template class are created as follows
class name <data type> object name;

template<class Ttype> int main()


class sample
{ I like C++ so much {
sample <int>s1;
Ttype a,b;
public: I like Rupesh sir sample <float>s2;
s1.getdata();
void getdata()
s1.sum();
{
s2.getdata();
cin>>a>>b;
s2.sum();
}
void sum(); }
};

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 30
template<class T1, class T2>
class Sample Class Template
{
T1 a; T2 b; Example
public:
Sample(T1 x,T2 y){
a=x;
b=y;
}
void disp(){
cout<<"\na="<<a<<"\
tb="<<b;  To create a class template
} object,
}; main(){
int define the data type
Sample <int,float> S1(12,23.3); inside a < > at the time of
Sample <char,int> S2('N',12); object creation.
S1.disp();  className<int> classObj;
S2.disp(); className<float> classObj;
}
GTU Programs
1. Write a function template for finding the minimum value
contained in an array.
2. Create a generic class stack using template and implement
common Push and Pop operations for different data types.
I like C++ so much
3. Write program to swap Number using Function Template.

I like Rupesh sir

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 32
STL – Standard Template Library

Stack Queue Vector

map
STL- Standard Template Library
 The C++ STL (Standard Template Library) is a powerful set of C++
template classes to provides general-purpose templatized classes
and functions that implement many popular and commonly used
algorithms and data structures like vectors, lists, queues, and


stacks.
I like C++ so much
There are three core components of STL as follows:
I like
1. Containers Rupesh
(an object to store data)sir
2. Algorithms (procedure to process data)
3. Iterators (pointer object to point elements in container)

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 34
STL- Containers
 A container is an object the actually stores data.
 The STL containers can be implemented by class templates to hold
different data types.

I like C++ so much Containers

SequenceI like Rupesh


Associative sir Derived
• vector • set • stack
• deque • multiset • queue
• list • map • Priority-
• multimap queue

Store elements in Direct access to Derived from sequence


linear sequence elements using keys containers

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 35
STL Algorithms
 It is a procedure that is used to process data contained in
containers.
 It includes algorithms that are used for initializing, searching,
copying, sorting and merging.
I like C++ so much
 Mutating Sequence Algorithms


I like Rupesh
Non Modifying sequence Algorithms
sir
like copy(), remove(), replace(), fill(), swap(), etc.,

like find(), count(),search(), mismatch(), and equal()


 Numerical Algorithms
accumulate(), partial_sum(), inner_product(), and
adjacent_difference()
Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 36
STL- Algorithms
 STL provide number of algorithms that can be used of any
container, irrespective of their type. Algorithms library contains
built in functions that performs complex algorithms on the data
structures.

I like C++ so much


 For example: one can reverse a range with reverse() function, sort
a range with sort() function, search in a range with binary_search()
and so on. I like Rupesh sir
 Algorithm library provides abstraction, i.e you don't necessarily
need to know how the the algorithm works.

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 37
STL- Iterations
 Iterators behave like pointers.
 Iterators are used to access container elements.
 They are used to traverse from one element to another.

I like C++ so much


I like Rupesh sir

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 38
STL components
 STL provides numerous containers and algorithms which are very
useful in completive programming , for example you can very
easily define a linked list in a single statement by using list
container of container library in STL , saving your time and effort.

I like C++ so much


 STL is a generic library , i.e a same container or algorithm can be
operated on any data types , you don’t have to define the same
I like Rupesh sir
algorithm for different type of elements.
 For example , sort algorithm will sort the elements in the given
range irrespective of their data type , we don’t have to implement
different sort algorithm for different datatypes.

Unit-8 Templates, Exceptions and STL Darshan Institute of Engineering & Technology 39
Thank You

You might also like