Templates - PowerPoint PPT Presentation

1 / 10
About This Presentation
Title:

Templates

Description:

A class template is like the 'raw material' for creating a class. ... Templates are used to design classes that can deal with various types of data ... – PowerPoint PPT presentation

Number of Views:43
Avg rating:3.0/5.0
Slides: 11
Provided by: mohamedab
Category:
Tags: templates

less

Transcript and Presenter's Notes

Title: Templates


1
Templates Exception Handling
  • What are templates ?
  • Use of templates.
  • Exception handling.
  • Main constituants of exception handling.
  • Use of exception handling.

2
Templates
  • A template is a programming tool aiming to
    promote code reuse.
  • A class template is like the raw material for
    creating a class.
  • When a template is used to produce a class, it is
    said that the template is instantiated, and the
    resulting class is called the generated class.
  • Templates are used to design classes that can
    deal with various types of data (int, float, ),
    and when the template is instantiated to generate
    a class, we have to specify the actual type that
    the class will deal with.
  • Syntax
  • template ltclass name_of_generic_typegt
  • class class_name
  • class members
  • int main(void)
  • class_name ltactual_typegt object_name( )

Name of generic type (any name that we choose)
will be replaced by the name of the actual type
(e.g. int) when we instantiate the templae to
generate a class.
Instantiation of the template with an actual type
(e.g. int, or a programmer-defined type), the
generated class is characterize by its name and
the actual type that replaces the generic type in
the template definition (i.e. the total class
name is class_namelttype_namegt).
3
Example1
include ltiostreamgt using namespace
std template ltclass typegt //template
definition class HeapStorage //type is
generic type name type head
//type will be replaced by the name of the
actual type (e.g. int) int noOfElements publi
c HeapStorage(int size 10) head
new typesize noOfElements size
void assignValue(int position, const type
value) if ((position gt0) (position lt
noOfElements-1)) headposition
value else cout ltlt
"boundary exceeded" ltlt endl type
getValue(int position) // method
prototype HeapStorage() // notice syntax
for methods defined outside the class template
ltclass typegt type HeapStoragelttypegt
getValue(int position) if ((position gt0)
(position lt noOfElements-1)) return
headposition else cout ltlt
"\nboundary exceeded" ltlt endl return
head0 template ltclass typegt HeapStoragelttype
gt HeapStorage() delete head
class Vector int x, y public
Vector(int u0, int v0) x u y v
friend ostream operator ltlt (ostream,
Vector) ostream operator ltlt (ostream os,
Vector V) os ltlt "\nx coordinate " ltlt V.x
os ltlt "\ty coordinate " ltlt V.y ltlt endl
return os
4
Example1 contd.
int main(void) HeapStorageltintgt s_int(5)
// instantiate the template with type
int s_int.assignValue(0, 15) cout ltlt
s_int.getValue(0) HeapStorageltfloatgt
s_float(10) // instantiate the template
with type float s_float.assignValue(0,
12.345) cout ltlt s_float.getValue(-1) HeapSto
rageltVectorgt s_vector(3) // instantiate the
template with type "Vector" Vector V1(2, 3),
V2(4, 5), V3 V3 s_vector.getValue(0) cout
ltlt V3 s_vector.assignValue(0, V2) V3
s_vector.getValue(0) cout ltlt V3 return 0
Output 15 boundary exceeded 12.345 x coordinate
0 y coordinate 0 x coordinate 4 y coordinate 5
5
Exception Handling
  • An exception is an error, and exception handling
    is the set of tools available to the programmer
    to determine program behavior in case of an
    exception.
  • Exception handling consists mainly of 3 parts
  • Determining the code (functions or methods) that
    could encounter errors while executing. Keyword
    throw
  • While executing this code we should check if it
    actually encountered an error. Keyword try
  • Handling the error if it occured. Keyword
    catch
  • The function (or method) that could encounter an
    error, and checks for the condition causing the
    error, is said to claim an exception.
  • If the error actually happens then the function
    throws the exception.
  • The code to be executed when the error actually
    occurs handles the exception.

6
Claiming an Exception
  • Claiming an exception means stating (in the
    function header) that the function could
    encounter errors and throw an exception.
  • Throwing an exception means passing a variable of
    a built-in type (or an object of a certain class)
    to another block of code that will act
    accordingly.
  • To claim an exception, the function should check
    for a certain condition (indicating an error) and
    throw an exception using the keyword ''throw''.
  • Syntax
  • return_type function_name (parameter_list) throw
    (list_of_types)code
  • Example
  • double getElement (int i) throw (bool)
  • if (i gt arraySize) // error condition
  • throw false
  • double x
  • x ptri
  • return x

This function throws an exception of type
boolean. Please Note throw() function throws no
exceptions. If the throw keyword is not mentioned
in the header, the function can throw an
exception of any type.
Note if the error condition is true and the
throw statement is executed, all statements after
it are ignored.
7
Handling an Exception
  • To handle an exception, we should first check to
    see if the exception was actually thrown (the
    error happened), we do this by a block of code
    called the try block.
  • Then we write the code that will be executed when
    the exception is thrown, we put this code in a
    block called the catch block.
  • To check if the exception was actually thrown
    (the error happened) the function that claims the
    exception must be put in a try block, otherwise
    the exception will go un-noticed and will not be
    handled.
  • A try block must be succeded by a catch block. A
    catch block can be preceded only by a try block
    or another catch block.
  • Example
  • try
  • double result getElement(5)
  • cout ltlt "value is " ltlt result ltlt endl
  • catch (bool b)
  • cout ltlt "array boundary exceeded\n"

Note if the function getElement() encountered an
error, and threw an exception, all statements
after it are ignored (the cout).
8
Some Notes
  • An exception is characterized by the type of the
    variable (or object) it throws.
  • If a function throws more than one exception,
    they must be of different types (classes), and
    one catch block has to be written for each type
    (class).
  • Example
  • double getElement (int i) throw (bool, int)
  • if (i gt arraySize) throw false
  • if (i lt 0) throw 1
  • double x
  • x ptri
  • return x
  • main ( )
  • try
  • double result getElement(5)
  • cout ltlt "value is " ltlt result ltlt endl
  • catch (bool b)
  • cout ltlt "array boundary exceeded\n"
  • catch (int i)
  • cout ltlt "index cannot be negative\n"

Note that when the function is called it is put
in a try block, because it claims exceptions.
Catching the 2 types of exceptions the function
can throw.
9
Example2
class List private int numOfNodes Node
const head Node last public
List()head(new Node(0)) numOfNodes
1 last head void
addNode(int i) Node ptr new Node(i)
last-gtnext ptr last ptr
numOfNodes void display(int
NthNode) throw (bool, indexException) if
(NthNode lt 0) throw false if (NthNode
gt numOfNodes-1) throw indexException()
cout ltlt "Value of node no. " ltlt NthNode ltlt " is
" Node current head, temp
for (int i 1 i lt NthNode i)
temp current -gt next current
temp cout ltlt current-gt value ltlt endl
List() Node current head,
temp for(int i0 i lt numOfNodes
i) temp current-gtnext
delete current current temp
include ltiostreamgt using namespace std class
Node private int value Node
next public Node(int i) value
i next NULL friend class
List class indexException char
str public indexException() str
"list boundary exceeded" void display()
cout ltlt endl ltlt str ltlt endl
10
Example2 contd.
int main( void ) List L L.addNode(12)
L.addNode(15) L.addNode(20) try
L.display(-1) catch(bool b)
cout ltlt "index cannot be negative\n"
catch(indexException ex) ex.display()
try L.display(15)
catch(bool b) cout ltlt "index cannot be
negative\n" catch(indexException ex)
ex.display() return 0
Output index cannot be negative list boundary
exceeded
Write a Comment
User Comments (0)
About PowerShow.com