SlideShare a Scribd company logo
1
2
3
Template

concept can be use in two
different concepts
i.
Function template
ii.
Class template

4
The

body of the function template is
written in the same way in each case
as function is written but the difference
is that they can handle arguments and
return value of different types.

5
Function Template

Template function:
template <class T>
void get(T a)
{
cout <<" value : "<<a;
cin.get();
}
void main()
{
int a=5;
float b=4.3;
get(a);
get(b);


}



Simple function:

void get(int a)
{
cout <<" value : "<<a;
cin.get();
getch();
}
void main()
{
int a=5;
float b=4.3;
get(a);
get(b);
}

6
Continued…



Function Template:



Simple Function

7
template <class T>
T square(T value)
{
return value*value;
}
int main()
{
int a=5;
float b=7.5;
long c=50000900000;
double d=784848.33;
cout<<"square of int variable is :
"<<square(a)<<endl;
cout<<"square of long variable is :
"<<square(b)<<endl;
cout<<"square of long variable is : "<<square
(c)<<endl;
cout<<"square of double variable is :
"<<square(d)<<endl;
cin.get();
getch();

8
template<class t >
void get( t x, t y , int c)
{
int sum;
sum=x+y+c;
cout<<sum;
cin.get();
getch();
}

void main()
{
int a=6;
int b=9;
int c=8;
get(a,b,c);
}

9
Function Template

template<class t, class v >
void get(t x, v y ,int c)
{
v sum;
sum=x+y+c;
cout<<sum;
cin.get();
getch();
}
void main()
{
int a=6;
float b=9.9;
int c=8;
get(a,b,c);
}

Output:

10
Class

template definition does not

change
Class template work for variable of all
types instead of single basic type

11
Class Template

template <class t>
class Basket
{
t first;
t second;
public:
Basket (t a, t b)
{
first = a;
second = b;
}
t Bat()
{
return (first > second?first:second);
}
}; //class end

void main()
{
Basket <int> bo(6,8);
cout<<bo.Bat()<<endl;
Basket <float> b1(1.1,3.3);
cout<<b1.Bat()<<endl;
system ("pause");
}

Output:
8
3.3

12
Continued…

If we write
Basket <int> b(6.99,8.88);
Instead of
Basket <int> b(6,8);
Output will be in integers i.e
8

13
Class Template

template <class t>
class Basket
{
t first;
t second;
public:
Basket (t a, t b)
{
first = a;
second = b;
}
t Big();
}; //class end
template <class t>
t Basket <t>::Big()
{
return (first > second?first:second);
}

void main()
{
Basket <int> b(6,8);
cout<<b.Big()<<endl;
Basket <float> b1(4.1,1.1);
cout<<b1.Big()<<endl;
system ("pause");
}

Output:
8
4.1

14
Continued…

template <class t>
t Basket <t>::Big()
{
return (first > second?first:second);

}
The

name Basket<t> is used to identify the
class of which Big() is a member function . In
a normal non-template member function the
name Basket alone would suffice.
Void Basket :: Big()
{
return (first > second?first:second);

}

15
Continued…

int Basket<int>::Big()
{
return (first > second?first:second);
}
float Basket<float>::Big()
{
return (first > second?first:second);
}
16
template<class TYPE>
struct link
{
TYPE data;
link* next;
};
template<class TYPE>
class linklist
{
private:
link<TYPE>* first;
public:
linklist()
{ first = NULL; }
void additem(TYPE d);
void display();
};

template<class TYPE>
void
linklist<TYPE>::additem(TYPE
d)
{
link<TYPE>* newlink = new
link<TYPE>;
newlink->data = d;
newlink->next = first;
first = newlink;
}
template<class TYPE>
void linklist<TYPE>::display()
{
link<TYPE>* current = first;
while( current != NULL )
17
Continued…

{

linklist<char> lch;

cout << endl << current->data;
current = current->next;
}
}

lch.additem('a');
lch.additem('b');
lch.additem('c');
lch.display();
cout << endl;
system("pause");

int main()
{
linklist<double> ld;
ld.additem(151.5);
ld.additem(262.6);
ld.additem(373.7);
ld.display();

}
OUTPUT
373.7
262.6
151.5
c
b
a

18
An

exception is a condition that
occurs at execution time and make
normal continuation of program
impossible.
When

an exception occurs, the
program must either terminate or jump
to special code for handling the
exception.
 Divide by zero errors.
 Accessing the element of an array beyond its
range
 Invalid input
 Hard disk crash
 Opening a non existent file
19
The

way of handling anomalous situations in a
program-run is known as exception handling.
Its advantage are:





Exception handling separate error-handling code from normal code.
It clarifies the code and enhances readability
Catch error s before it occurs.
It makes for clear, robust and fault -tolerant program s.

20






Tries a block of code that may contain
exception
Throws an exception when one is detected
Catches the exception and handles it
Thus there are three concepts
i. The try block
ii.The throwing of the exception
iii.The catch block

21


A block which includes the code that may
generate the error(an exception)
try { ….
}






Can be followed by one or more catch blocks
which handles the exception
Control of the program passes from the
statements in the try block ,to the appropriate
catch block.
Functions called try block, directly or
indirectly, could test for the presence of the
error
22




Used to indicate that an exception has occurred
Will be caught by closest exception handler
Syntax:if ( // error)
{
Throw error();
}

23
Contain the exception handler.
 These know what to do with the exceptiontypically print out that a type of error has
occurred.
 Catch blocks are typically located right after
the try block that could throw the exception
Syntax:catch()
{
…..
}


24
25
Exceptions

const int DivideByZero = 10;
double divide(double x, double
y)
{
if(y==0)
{
throw DivideByZero;
}
return x/y;
}
int main()
{
try
{
divide(10, 0);
}

catch(int i)
{
if(i==DivideByZero)
{
cout<<"Divide by zero
error";
}
cin.get();
}}

Output:Divide by zero
error

26
















Class Aclass
{
Public:
Class Anerror
{
};
Void func()
{
if(/*error condition*/)
Throw Anerror();
}
};

Int main()
{
Try
{
Aclass object1;
Object1.fun();
}
Catch (Aclass ::Anerror) //may
cause error
{
//tell user about error
}
Return 0;
}

27
try
{
//try block
}
catch(type1 arg)
{
//catch block1
}
catch(type2 arg)
{
//catch block2
}

…….
…….
catch(typeN arg)
{
//catch blockN
}

28
Multiple Exceptions

const int Max=3;
class stack
{private:
int st[Max],top;
public:
class full
{};
Class empty
{};
stack()
{top=-1;
}

void push(int var)
{
if(top>=Max-1)
throw full();
st[++top]=var;
}
Int pop()
{if(top<0)
Throw empty();
Return st [top--];
}
};
29
Continued…

int main()
{stack s1;
try
{
s1.push(11); s1.push(22);
s1.push(33); s1.push(44);
S1.pop();
s1.pop();
S1.pop();
s1.pop();
}
catch(stack::full)
{
cout<<"exception :stack
full"<<endl;
}

Catch(stack::empty)
{
Cout<<“exception: stack
empty”<<endl;
}
cin.get();
}

30
class Distance
{
private:
int feet;
float inches;
public:
class InchesEx { };
Distance()
{ feet = 0; inches = 0.0; }
Distance(int ft, float in)
{
if(in >= 12.0)
throw InchesEx();
feet = ft;
inches = in;
}

void getdist()
{
cout << "nEnter feet: "; cin >>
feet;
cout << "Enter inches: "; cin >>
inches;
if(inches >= 12.0)
throw InchesEx();
}
void showdist()
{ cout << feet << "’-" << inches; }
};

31
Continued…
int main()
{
try
{
Distance dist1(17, 3.5);
Distance dist2;
dist2.getdist();
cout << "ndist1 = "; dist1.showdist();
cout << "ndist2 = "; dist2.showdist();
}
catch(Distance::InchesEx)
{
cout << "nInitialization error: ";
cout<< "inches value is too large.";
}
cout << endl;
return 0;
}

32
class Distance
{
private:
int feet;
float inches;
public:
class InchesEx
{
public:
string origin;
float iValue;
InchesEx(string or, float in)
{
origin = or;
iValue = in;
}
};

Distance()
{ feet = 0; inches = 0.0; }
Distance(int ft, float in)
{
if(in >= 12.0)
throw InchesEx("2-arg
constructor", in);
feet = ft;
inches = in;
}
void getdist()
{
cout << "nEnter feet: "; cin >>
feet;
cout << "Enter inches: "; cin >>
inches;
33
Continued…

if(inches >= 12.0)
throw InchesEx("getdist()
function", inches);
}
void showdist()
{ cout << feet << "’-" << inches;
}
};
void main()
{
try
{
Distance dist1(17, 3.5);
Distance dist2;

dist2.getdist();
cout << "ndist1 = ";
dist1.showdist();
cout << "ndist2 = ";
dist2.showdist();
}
catch(Distance::InchesEx ix)
{
cout << "nInitialization error in
" << ix.origin
<< ".n Inches value of " <<
ix.iValue
<< " is too large.";
}
34
class InchesEx
{
public:
string origin;
float iValue;
InchesEx(string or, float in)
{
origin = or;
iValue = in;
}
};
35


Extracting data from the exception object
int main()
{
const unsigned long SIZE = 10000;
char* ptr;
try
{
ptr = new char[SIZE];
}
catch(bad_alloc)
{
cout << “nbad_alloc exception: can’t
allocate memory.n”;
return(1);
}
delete[] ptr; //deallocate memory
cout << “nMemory use is successful.n”;
return 0;
}

36

More Related Content

What's hot

More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and ObjectsPayel Guria
 
Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in Swift
Netguru
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
tdc-globalcode
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
ssuserd6b1fd
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
DEVTYPE
 
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
ssuserd6b1fd
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
tdc-globalcode
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
ssuserd6b1fd
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
Alfonso Peletier
 
Implementing stack
Implementing stackImplementing stack
Implementing stack
mohamed sikander
 
Java cheatsheet
Java cheatsheetJava cheatsheet
Java cheatsheet
Anass SABANI
 
Networking Core Concept
Networking Core ConceptNetworking Core Concept
Networking Core Concept
Rays Technologies
 
Pointer
PointerPointer
C tech questions
C tech questionsC tech questions
C tech questions
vijay00791
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Lorna Mitchell
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
Garth Gilmour
 
C programs
C programsC programs
C programs
Vikram Nandini
 
Stl algorithm-Basic types
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic types
mohamed sikander
 

What's hot (19)

More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and Objects
 
Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in Swift
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
Implementing stack
Implementing stackImplementing stack
Implementing stack
 
Java cheatsheet
Java cheatsheetJava cheatsheet
Java cheatsheet
 
Networking Core Concept
Networking Core ConceptNetworking Core Concept
Networking Core Concept
 
Pointer
PointerPointer
Pointer
 
C tech questions
C tech questionsC tech questions
C tech questions
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
C programs
C programsC programs
C programs
 
Stl algorithm-Basic types
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic types
 

Viewers also liked

Rozmowa doradcza
Rozmowa doradczaRozmowa doradcza
Rozmowa doradcza
Ojejuilemozna
 
Rozmowa doradcza
Rozmowa doradczaRozmowa doradcza
Rozmowa doradcza
Ojejuilemozna
 
Najpiękniejsze miejsca na świecie
Najpiękniejsze miejsca na świecieNajpiękniejsze miejsca na świecie
Najpiękniejsze miejsca na świeciezsStb
 
Presentation on template and exception
Presentation  on template and exceptionPresentation  on template and exception
Presentation on template and exception
Sajid Alee Mosavi
 
Makalah jaringan-komputer
Makalah jaringan-komputerMakalah jaringan-komputer
Makalah jaringan-komputer
Medok Zoya
 
UTE "OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA"
UTE "OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA"UTE "OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA"
UTE "OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA"Tatiana Cobena Tayo
 
UTE OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA
UTE OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULAUTE OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA
UTE OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA
Tatiana Cobena Tayo
 
Rozmowa doradcza
Rozmowa doradczaRozmowa doradcza
Rozmowa doradcza
Ojejuilemozna
 
Sistem imun
Sistem imunSistem imun
Sistem imun
Ahmad Raihan
 
Rozmowa doradcza 12
Rozmowa doradcza 12Rozmowa doradcza 12
Rozmowa doradcza 12
Ojejuilemozna
 
Sistem imun
Sistem imunSistem imun
Sistem imun
Ahmad Raihan
 
Zalety i wady internetu
Zalety i wady internetuZalety i wady internetu
Zalety i wady internetuzsStb
 

Viewers also liked (15)

Rozmowa doradcza
Rozmowa doradczaRozmowa doradcza
Rozmowa doradcza
 
Rozmowa doradcza
Rozmowa doradczaRozmowa doradcza
Rozmowa doradcza
 
Najpiękniejsze miejsca na świecie
Najpiękniejsze miejsca na świecieNajpiękniejsze miejsca na świecie
Najpiękniejsze miejsca na świecie
 
Emoticonos
EmoticonosEmoticonos
Emoticonos
 
Presentation on template and exception
Presentation  on template and exceptionPresentation  on template and exception
Presentation on template and exception
 
Makalah jaringan-komputer
Makalah jaringan-komputerMakalah jaringan-komputer
Makalah jaringan-komputer
 
UTE "OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA"
UTE "OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA"UTE "OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA"
UTE "OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA"
 
UTE OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA
UTE OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULAUTE OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA
UTE OTRAS VARIABLES QUE DETERMINAN LA DIVERSIDAD EN EL AULA
 
fungi
fungi fungi
fungi
 
Rozmowa doradcza
Rozmowa doradczaRozmowa doradcza
Rozmowa doradcza
 
Sistem imun
Sistem imunSistem imun
Sistem imun
 
Rozmowa doradcza 12
Rozmowa doradcza 12Rozmowa doradcza 12
Rozmowa doradcza 12
 
Rozmowa doradcza
Rozmowa doradczaRozmowa doradcza
Rozmowa doradcza
 
Sistem imun
Sistem imunSistem imun
Sistem imun
 
Zalety i wady internetu
Zalety i wady internetuZalety i wady internetu
Zalety i wady internetu
 

Similar to Pre zen ta sion

C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 
Pads lab manual final
Pads lab manual finalPads lab manual final
Pads lab manual final
AhalyaR
 
Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.ppt
instaface
 
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxlab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
DIPESH30
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
 
New presentation oop
New presentation oopNew presentation oop
New presentation oop
Ch shampi Ch shampi
 
Xiicsmonth
XiicsmonthXiicsmonth
Xiicsmonth
rishikasahu1908
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
Mouna Guru
 
Intro to c programming
Intro to c programmingIntro to c programming
Intro to c programming
Prabhu Govind
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
Templates
TemplatesTemplates
Templates
Farwa Ansari
 
C++ prgms 3rd unit
C++ prgms 3rd unitC++ prgms 3rd unit
C++ prgms 3rd unit
Ananda Kumar HN
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2Technopark
 
Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
hanumanthu mothukuru
 

Similar to Pre zen ta sion (20)

C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
C++ programs
C++ programsC++ programs
C++ programs
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
Pads lab manual final
Pads lab manual finalPads lab manual final
Pads lab manual final
 
Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.ppt
 
oop objects_classes
oop objects_classesoop objects_classes
oop objects_classes
 
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxlab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Tu1
Tu1Tu1
Tu1
 
New presentation oop
New presentation oopNew presentation oop
New presentation oop
 
Xiicsmonth
XiicsmonthXiicsmonth
Xiicsmonth
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 
Intro to c programming
Intro to c programmingIntro to c programming
Intro to c programming
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
Templates
TemplatesTemplates
Templates
 
C++ prgms 3rd unit
C++ prgms 3rd unitC++ prgms 3rd unit
C++ prgms 3rd unit
 
Ss
SsSs
Ss
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
 
Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
 

Recently uploaded

Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 

Recently uploaded (20)

Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 

Pre zen ta sion

  • 1. 1
  • 2. 2
  • 3. 3
  • 4. Template concept can be use in two different concepts i. Function template ii. Class template 4
  • 5. The body of the function template is written in the same way in each case as function is written but the difference is that they can handle arguments and return value of different types. 5
  • 6. Function Template Template function: template <class T> void get(T a) { cout <<" value : "<<a; cin.get(); } void main() { int a=5; float b=4.3; get(a); get(b);  }  Simple function: void get(int a) { cout <<" value : "<<a; cin.get(); getch(); } void main() { int a=5; float b=4.3; get(a); get(b); } 6
  • 8. template <class T> T square(T value) { return value*value; } int main() { int a=5; float b=7.5; long c=50000900000; double d=784848.33; cout<<"square of int variable is : "<<square(a)<<endl; cout<<"square of long variable is : "<<square(b)<<endl; cout<<"square of long variable is : "<<square (c)<<endl; cout<<"square of double variable is : "<<square(d)<<endl; cin.get(); getch(); 8
  • 9. template<class t > void get( t x, t y , int c) { int sum; sum=x+y+c; cout<<sum; cin.get(); getch(); } void main() { int a=6; int b=9; int c=8; get(a,b,c); } 9
  • 10. Function Template template<class t, class v > void get(t x, v y ,int c) { v sum; sum=x+y+c; cout<<sum; cin.get(); getch(); } void main() { int a=6; float b=9.9; int c=8; get(a,b,c); } Output: 10
  • 11. Class template definition does not change Class template work for variable of all types instead of single basic type 11
  • 12. Class Template template <class t> class Basket { t first; t second; public: Basket (t a, t b) { first = a; second = b; } t Bat() { return (first > second?first:second); } }; //class end void main() { Basket <int> bo(6,8); cout<<bo.Bat()<<endl; Basket <float> b1(1.1,3.3); cout<<b1.Bat()<<endl; system ("pause"); } Output: 8 3.3 12
  • 13. Continued… If we write Basket <int> b(6.99,8.88); Instead of Basket <int> b(6,8); Output will be in integers i.e 8 13
  • 14. Class Template template <class t> class Basket { t first; t second; public: Basket (t a, t b) { first = a; second = b; } t Big(); }; //class end template <class t> t Basket <t>::Big() { return (first > second?first:second); } void main() { Basket <int> b(6,8); cout<<b.Big()<<endl; Basket <float> b1(4.1,1.1); cout<<b1.Big()<<endl; system ("pause"); } Output: 8 4.1 14
  • 15. Continued… template <class t> t Basket <t>::Big() { return (first > second?first:second); } The name Basket<t> is used to identify the class of which Big() is a member function . In a normal non-template member function the name Basket alone would suffice. Void Basket :: Big() { return (first > second?first:second); } 15
  • 16. Continued… int Basket<int>::Big() { return (first > second?first:second); } float Basket<float>::Big() { return (first > second?first:second); } 16
  • 17. template<class TYPE> struct link { TYPE data; link* next; }; template<class TYPE> class linklist { private: link<TYPE>* first; public: linklist() { first = NULL; } void additem(TYPE d); void display(); }; template<class TYPE> void linklist<TYPE>::additem(TYPE d) { link<TYPE>* newlink = new link<TYPE>; newlink->data = d; newlink->next = first; first = newlink; } template<class TYPE> void linklist<TYPE>::display() { link<TYPE>* current = first; while( current != NULL ) 17
  • 18. Continued… { linklist<char> lch; cout << endl << current->data; current = current->next; } } lch.additem('a'); lch.additem('b'); lch.additem('c'); lch.display(); cout << endl; system("pause"); int main() { linklist<double> ld; ld.additem(151.5); ld.additem(262.6); ld.additem(373.7); ld.display(); } OUTPUT 373.7 262.6 151.5 c b a 18
  • 19. An exception is a condition that occurs at execution time and make normal continuation of program impossible. When an exception occurs, the program must either terminate or jump to special code for handling the exception.  Divide by zero errors.  Accessing the element of an array beyond its range  Invalid input  Hard disk crash  Opening a non existent file 19
  • 20. The way of handling anomalous situations in a program-run is known as exception handling. Its advantage are:     Exception handling separate error-handling code from normal code. It clarifies the code and enhances readability Catch error s before it occurs. It makes for clear, robust and fault -tolerant program s. 20
  • 21.     Tries a block of code that may contain exception Throws an exception when one is detected Catches the exception and handles it Thus there are three concepts i. The try block ii.The throwing of the exception iii.The catch block 21
  • 22.  A block which includes the code that may generate the error(an exception) try { …. }    Can be followed by one or more catch blocks which handles the exception Control of the program passes from the statements in the try block ,to the appropriate catch block. Functions called try block, directly or indirectly, could test for the presence of the error 22
  • 23.    Used to indicate that an exception has occurred Will be caught by closest exception handler Syntax:if ( // error) { Throw error(); } 23
  • 24. Contain the exception handler.  These know what to do with the exceptiontypically print out that a type of error has occurred.  Catch blocks are typically located right after the try block that could throw the exception Syntax:catch() { ….. }  24
  • 25. 25
  • 26. Exceptions const int DivideByZero = 10; double divide(double x, double y) { if(y==0) { throw DivideByZero; } return x/y; } int main() { try { divide(10, 0); } catch(int i) { if(i==DivideByZero) { cout<<"Divide by zero error"; } cin.get(); }} Output:Divide by zero error 26
  • 27.             Class Aclass { Public: Class Anerror { }; Void func() { if(/*error condition*/) Throw Anerror(); } }; Int main() { Try { Aclass object1; Object1.fun(); } Catch (Aclass ::Anerror) //may cause error { //tell user about error } Return 0; } 27
  • 28. try { //try block } catch(type1 arg) { //catch block1 } catch(type2 arg) { //catch block2 } ……. ……. catch(typeN arg) { //catch blockN } 28
  • 29. Multiple Exceptions const int Max=3; class stack {private: int st[Max],top; public: class full {}; Class empty {}; stack() {top=-1; } void push(int var) { if(top>=Max-1) throw full(); st[++top]=var; } Int pop() {if(top<0) Throw empty(); Return st [top--]; } }; 29
  • 30. Continued… int main() {stack s1; try { s1.push(11); s1.push(22); s1.push(33); s1.push(44); S1.pop(); s1.pop(); S1.pop(); s1.pop(); } catch(stack::full) { cout<<"exception :stack full"<<endl; } Catch(stack::empty) { Cout<<“exception: stack empty”<<endl; } cin.get(); } 30
  • 31. class Distance { private: int feet; float inches; public: class InchesEx { }; Distance() { feet = 0; inches = 0.0; } Distance(int ft, float in) { if(in >= 12.0) throw InchesEx(); feet = ft; inches = in; } void getdist() { cout << "nEnter feet: "; cin >> feet; cout << "Enter inches: "; cin >> inches; if(inches >= 12.0) throw InchesEx(); } void showdist() { cout << feet << "’-" << inches; } }; 31
  • 32. Continued… int main() { try { Distance dist1(17, 3.5); Distance dist2; dist2.getdist(); cout << "ndist1 = "; dist1.showdist(); cout << "ndist2 = "; dist2.showdist(); } catch(Distance::InchesEx) { cout << "nInitialization error: "; cout<< "inches value is too large."; } cout << endl; return 0; } 32
  • 33. class Distance { private: int feet; float inches; public: class InchesEx { public: string origin; float iValue; InchesEx(string or, float in) { origin = or; iValue = in; } }; Distance() { feet = 0; inches = 0.0; } Distance(int ft, float in) { if(in >= 12.0) throw InchesEx("2-arg constructor", in); feet = ft; inches = in; } void getdist() { cout << "nEnter feet: "; cin >> feet; cout << "Enter inches: "; cin >> inches; 33
  • 34. Continued… if(inches >= 12.0) throw InchesEx("getdist() function", inches); } void showdist() { cout << feet << "’-" << inches; } }; void main() { try { Distance dist1(17, 3.5); Distance dist2; dist2.getdist(); cout << "ndist1 = "; dist1.showdist(); cout << "ndist2 = "; dist2.showdist(); } catch(Distance::InchesEx ix) { cout << "nInitialization error in " << ix.origin << ".n Inches value of " << ix.iValue << " is too large."; } 34
  • 35. class InchesEx { public: string origin; float iValue; InchesEx(string or, float in) { origin = or; iValue = in; } }; 35
  • 36.  Extracting data from the exception object int main() { const unsigned long SIZE = 10000; char* ptr; try { ptr = new char[SIZE]; } catch(bad_alloc) { cout << “nbad_alloc exception: can’t allocate memory.n”; return(1); } delete[] ptr; //deallocate memory cout << “nMemory use is successful.n”; return 0; } 36