templates

55

Upload: farwa-ansari

Post on 16-Apr-2017

984 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Templates
Page 2: Templates

Presentation of: Programming Fundamentals

Presented to: Sir Omair Ashraf Presented by: Aniqa Farwa A.H

Ammarah

Page 3: Templates

Templates

Page 4: Templates

Templates:Definition:

Templates are used to define generic definition of functions or classes.

A template is not related to specific data types and can work with different data types.

Can re-use same code with int, string, etc.

Page 5: Templates

Types of Templates:

There are two types of templates:

Function templatesClass templates

Page 6: Templates

Function Templates: Function templates are special functions that can

operate with generic types.

This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.

Same code is re-used for different types

Page 7: Templates

Function Templates: Syntax: template <class T> T FunctionName (Parameter (s));

Page 8: Templates

Function Templates:Example:#include<iostream.h>#include<conio.h> using namespace std; template<class T> void swap(T&x,T &y) {   t temp=x;   x=y;   y=temp;} void fun(int a,int b,float c,float d){   cout<<"\na and b before swaping :"<<a<<"\t"<<b;   swap(a,b);   cout<<"\na and b after

swaping  :"<<a<<"\t"<<b;   cout<<"\n\nc and d before swaping :"<<c<<"\t"<<d;   swap(c,d);   cout<<"\nc and d after swaping  :"<<c<<"\t"<<d;}

void main(){    int a,b;    float c,d;    clrscr();    cout<<"Enter A,B values(integer):";    cin>>a>>b;    cout<<"Enter C,D values(float):";    cin>>c>>d;    fun(a,b,c,d);    getch();}

Page 9: Templates

Function Templates:Output:Enter A, B values (integer): 10  20Enter C, D values (float):    2.50  10.80 A and B before swapping: 10 20A and B after    swapping:  20 10 C and D before swapping: 2.50  10.80C and D after  swapping: 10.80  2.50

Page 10: Templates

Function Templates:Program:

#include<iostream>#include<conio.h>using namespace std;template <class Type> Type Max(Type a, Type b){ if(a>b) return a; else return b;}Void main(){int n;float m;

n=Max(10, 50);cout<<“Maximum of two integers:“<<n<<endl;m=Max(4.8, 2.2);Cout<<“Maximum of two float: “<<m<<endl;getch();}

Output:

Maximum of two integers: 50

Maximum of two floats:4.8

Page 11: Templates

Class Templates

By: Farwa Abdul Hannan

Page 12: Templates

Introduction Class templates are generally

used for data storage classes. Stacks and linked lists are

examples of data storage classes. The examples of these

classes(data storage classes) that we present could store data of only a single basic type.

Page 13: Templates

Example

The example shown, could store data only of type “int” that is:

Page 14: Templates

Example that stores data of a single type:

class Stack {

› private: int st[MAX]; //array of int int top; //index number of top of stack

› public: Stack(); //constructor void push(int var); //takes int as argument int pop(); //returns int value

};

Page 15: Templates

Another example

If we wanted to store data of type long in a stack, we would need to define a completely new class.

Page 16: Templates

Example that stores data of a single type:

class LongStack {

› private: long st[MAX]; //array of longs long top; //index number of top of

stack› public:

LongStack(); //constructor void push(long var); //takes long as

argument long pop(); //returns long

value };

Page 17: Templates

Benefit of class templates

Templates make it possible to use one function or class to handle different data types.

Page 18: Templates

Syntax The basic syntax for

declaring template class:

template <class Type> class Cont {

› …… };

Page 19: Templates

Example

Example of class template that handle variables of all / different data types is shown

Page 20: Templates

// tempstak.cpp // implements stack class as a template #include <iostream.h> using namespace std; const int MAX = 100; //size of array template <class Type> class Stack { private: Type st[MAX]; //stack: array of any type int top; //number of top of stack public: Stack() //constructor { top = -1; } void push(Type var) //put number on stack { st[++top] = var; } Type pop() //take number off stack { return st[top--]; } };

Page 21: Templates

int main() { Stack<float> s1; //s1 is object of class Stack<float> s1.push(1111.1F); //push 3 floats, pop 3 floats s1.push(2222.2F); s1.push(3333.3F); cout << “1: “ << s1.pop() << endl; cout << “2: “ << s1.pop() << endl; cout << “3: “ << s1.pop() << endl; Stack<long> s2; //s2 is object of class Stack<long> s2.push(123123123L); //push 3 longs, pop 3 longs s2.push(234234234L); s2.push(345345345L); cout << “1: “ << s2.pop() << endl; cout << “2: “ << s2.pop() << endl; cout << “3: “ << s2.pop() << endl; return 0; }

Page 22: Templates

Output of previous code

1: 3333.3 //float stack 2: 2222.2 3: 1111.1 1: 345345345 //long stack 2: 234234234 3: 123123123

Page 23: Templates

Flow chart representation

Page 24: Templates

Specification Class templates differ from function

templates in the way they are instantiated.

To create an actual function from a function template, you call it using arguments of a specific type.

Page 25: Templates

ExceptionsBy: Ammarah Khalid

Roll No.:1

Page 26: Templates

Why do we need Exceptions?

Old C language signaled many errors for returning a particular value from the functions.

Setjump() and Longjump() functions were used for handling errors there (very difficult to use).

This approach is not appropriate in C++.

It handles errors in a different way using “Exceptions”.

Page 27: Templates

Exceptions Syntax:

The exception syntax consists of: First of all, there should be an

exception class. Throw Exception (To handle an error) Try Block (A code that uses objects) Catch Block (Catches exception

through member function)

Page 28: Templates

Continue Exception Syntax:

Page 29: Templates

A General Example: // not a working program class AClass //a class { public: class AnError //exception class { }; void Func() //a member function { if( /* error condition */ ) throw AnError(); //throw exception } }; int main() //application { try //try block { AClass obj1; //interact with AClass objects obj1.Func(); //may cause error } catch(AClass::AnError) //exception handler { //(catch block) //tell user about error, etc. } return 0; }

Page 30: Templates

A Code Example: // demonstrates exceptions #include <iostream> using namespace std; const int MAX = 3; //stack holds 3 integers class Stack { private: int st[MAX]; //array of integers int top; //index of top of stack public: class Range //exception class for Stack { //note: empty class body };

Page 31: Templates

Continue.. Stack() //constructor { top = -1; } void push(int var) { if(top >= MAX-1) //if stack full, throw Range(); //throw exception st[++top] = var; //put number on stack } int pop() { if(top < 0) //if stack empty, throw Range(); //throw exception return st[top--]; //take number off stack } };

Page 32: Templates

Continue.. int main() { Stack s1; try { s1.push(11); s1.push(22); s1.push(33); // s1.push(44); //oops: stack full cout << “1: “ << s1.pop() << endl; cout << “2: “ << s1.pop() << endl; cout << “3: “ << s1.pop() << endl; cout << “4: “ << s1.pop() << endl; //oops: stack empty catch(Stack::Range) //exception handler { cout << “Exception: Stack Full or Empty” << endl; } cout << “Arrive here after catch (or normal exit)” << endl; return 0; }

Page 33: Templates

Output:

Page 34: Templates

Specifying Exception Class:

First of all, exception class should be specified as follows:

Class Range { empty class body};

Page 35: Templates

Throwing an Exception: Exception will occur in previous

program if application tries to pop a value when stack is empty and push a value when stack is full.

Throw Range() will perform this task here.

Page 36: Templates

Try Block: Statements that manipulate stack

(class name) objects, are enclosed in try block.

try { //code that operates on objects that

might cause exception }

Page 37: Templates

Exception Handler: Code that handles exceptions is

enclosed in braces, preceded by catch keyword.

catch(stack::Range) { //code that handles exception }

Page 38: Templates

Sequence of Events: Normal execution outside try block. Control enters the try block. An error occurs in try block (in main

function). Member function throws an exception. Control transfers to exception handler.

Page 39: Templates

Multiple Exceptions Example:

// demonstrates two exception handlers #include <iostream> using namespace std; const int MAX = 3; //stack holds 3 integers class Stack { private: int st[MAX]; //stack: array of integers int top; //index of top of stack public: class Full { }; //exception class class Empty { }; //exception class Stack() //constructor { top = -1; } void push(int var) //put number on stack { if(top >= MAX-1) //if stack full, throw Full(); //throw Full exception st[++top] = var; }

Page 40: Templates

Continue.. int pop() //take number off stack { if(top < 0) //if stack empty, throw Empty(); //throw Empty exception return st[top--]; } }; int main() { Stack s1; try { s1.push(11); s1.push(22);

Page 41: Templates

Continue.. s1.push(33); // s1.push(44); //oops: stack full cout << “1: “ << s1.pop() << endl; cout << “2: “ << s1.pop() << endl; cout << “3: “ << s1.pop() << endl; cout << “4: “ << s1.pop() << endl; //oops: stack empty } catch(Stack::Full) { cout << “Exception: Stack Full” << endl; } catch(Stack::Empty) { cout << “Exception: Stack Empty” << endl; } return 0; }

Page 42: Templates

Output:

Page 43: Templates

Exceptions with Arguments:

// exceptions with arguments #include <iostream> #include <string> using namespace std; class Distance //English Distance class { private: int feet; float inches; public class InchesEx //exception class {

Page 44: Templates

Continue.. public: string origin; //for name of routine float iValue; //for faulty inches value InchesEx(string or, float in) //2-arg constructor { origin = or; //store string iValue = in; //store inches } }; //end of exception class Distance() //constructor (no args) { feet = 0; inches = 0.0; }

Page 45: Templates

Continue.. Distance(int ft, float in) //constructor (two

args) { if(in >= 12.0) throw InchesEx(“2-arg constructor”, in); feet = ft; inches = in; } void getdist() //get length from user { cout << “\nEnter feet: “; cin >> feet; cout << “Enter inches: “; cin >> inches;

Page 46: Templates

Continue.. if(inches >= 12.0) throw InchesEx(“getdist() function”, inches); } void showdist() //display distance { cout << feet << “\’-” << inches << ‘\”’; } }; int main() { Distance dist1(17, 3.5); //2-arg constructor Distance dist2; //no-arg constructor dist2.getdist(); //get value //display distances

Page 47: Templates

Continue.. cout << “\ndist1 = “; dist1.showdist(); cout << “\ndist2 = “; dist2.showdist(); } catch(Distance::InchesEx ix) //exception handler { cout << “\nInitialization error in “ << ix.origin << “.\n Inches value of “ << ix.iValue << “ is too large.”; } cout << endl; return 0; }

Page 48: Templates

Output:

Page 49: Templates

Function Nesting: The exception statements need not be

in the try block directly. It can be in a function that is called by

a statement in try block. However, try part must be included

before catch part.

Page 50: Templates

Exceptions and Class Libraries:

The class libraries sold by any developer may contain errors. They can cause problems. These problems can be resolved using Exceptions.

Page 51: Templates

Not for Every Situation: Do not use exceptions for simple

purposes that can be solved using loops and other structures. Use exceptions for handling difficult tasks only because they effect the program size.

Page 52: Templates

Destructors called Automatically:

In exception mechanism, destructors are called automatically. So the space reserved by them is swiped clean easily.

Code in every exception will be reset.

Page 53: Templates

Handling Exceptions: When you catch an exception,

sometimes you terminate your application. Exception mechanism cleans up chores before terminating. In short, it executes destructors. If there is no exception handler, the program is terminated by operating system.

Page 54: Templates

It’s all about..Try-Throw-Catch

Page 55: Templates

THANK YOU