OODP-Unit_4 (1)
OODP-Unit_4 (1)
UNIT-4
• Generic - Templates - Function templates -
Class Templates
• Exceptional Handling: try and catch -
Multilevel exceptional - throw and throws -
finally - User defined exceptional
• Dynamic Modeling: Package Diagram - UML
Component Diagram - UML Deployment
Diagram
Topic :Generic - Templates :
Introduction
Templates-Introduction
• Allows functions and classes to operate with generic
types.
• Allows a function or class to work on many
different data types without being rewritten for each
one.
• Great utility when combined with multiple inheritance
and operator overloading
• The C++ Standard Library is based upon conventions
introduced by the Standard Template Library (STL)
Types of Templates
• Function Template
A function template behaves like a
function except that the template can have arguments
of many different types
• Class Template
A class template provides a specification
for generating classes based on parameters.
Class templates are generally used to
implement containers.
Function Template
• A function templates work in similar manner as function but with
one key difference.
• A single function template can work on different types at once
but, different functions are needed to perform identical task on
different data types.
• If you need to perform identical operations on two or more types
of data then, you can use function overloading. But better
approach would be to use function templates because you can
perform this task by writing less code and code is easier to
maintain.
Cont.
• A generic function that represents several functions
performing same task but on different data types is called
function template.
• For example, a function to add two integer and float numbers
requires two functions. One function accept integer types and
the other accept float types as parameters even though the
functionality is the same. Using a function template, a single
function can be used to perform both additions.
• It avoids unnecessary repetition of code for doing same task on
various data types.
Cont.
Why Function Templates?
• Templates are instantiated at compile-time with the
source code.
• Templates are used less code than overloaded C++
functions.
• Templates are type safe.
• Templates allow user-defined specialization.
• Templates allow non-type parameters.
Function Template
• A function template starts with keyword template
followed by template parameter/s inside <> which is
followed by function declaration.
• T is a template argument and class is a keyword.
• We can also use keyword typename instead of class.
• When, an argument is passed to some_function( ),
compiler generates new version of some_function() to
work on argument of that type.
Template Syntax
template <class T>
T some_function(T argument)
{
.... ... ....
}
Invoking function
functionName<dataType>(parameter1, parameter2,...);
Method Overloading Template Function
Calling a Function Template
return 0;
}
Execution Procedure
Example program Function Templates
#include<iostream.h>
using namespace std;
Examples:
className <int> classObject;
className <float> classObject;
className <string> classObject;
// Class template
template <class T> int main()
class Number {
{ Number <int> n1(7);
private: Number <double> n2(7.7);
T num; cout << "int Number = " << n1.getNum() << endl;
cout << "double Number = " << n2.getNum() << endl;
public: return 0;
Number(T n) : num(n) }
{
T getNum()
{
return num;
}
};
Example Program
#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--]; }
};
Cont.
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); St[2] 3333.3F
s1.push(3333.3F); St[1] 2222.2F
cout << “1: “ << s1.pop() << endl; St[0] 1111.1F
cout << “2: “ << s1.pop() << endl;
cout << “3: “ << s1.pop() << endl;
3)Which among the following is the proper syntax for the template class?
a) template <typename T1, typename T2>;
b) Template <typename T1, typename T2>;
c) template <typename T> T named(T x, T y){ }
d) Template <typename T1, typename T2> T1 named(T1 x, T2 y){ }
1) Find the Output
#include <iostream>
using namespace std;
template <typename T>
void fun(const T&x)
{
static int count = 0;
cout << "x = " << x << " count = " << count;
++count;
return;
}
int main()
{
fun<int> (1);
cout << endl;
fun<int>(1);
cout << endl;
fun<double>(1.1);
cout << endl;
return 0;
}
Choices
#include <iostream>
using namespace std;
template <typename T1, typename T2> a) 7 7.0 7.0
T1 max1(T1 x, T2 y) b) 7 7 7.2
{ c) 7 7.0 7.0
return (x > y)? x : y;
} d) error
int main()
{
cout << max1(3, 7) << endl;
cout << max1(3.2, 7) << endl;
cout << max1(3.1, 7.2) << endl;
return 0;
}
Execute in Laptop and find the output
#include <iostream>
using namespace std;
template <class T>
class Test
{
private:
T val;
public:
static int count;
Test() {
count++;
}};
template<class T>
int Test<T>::count = 0;
int main()
{
Test<int> a;
Test<int> b;
Test<double> c;
cout << Test<int>::count << endl;
cout << Test<double>::count << endl;
return 0;
}
Execute in Laptop and find the output
#include<iostream>
#include<stdlib.h>
using namespace std;
template<class T, class U>
class A
{
T x;
U y;
};
int main() {
A<char, char> a;
A<int, int> b;
cout << sizeof(a) << endl;
cout << sizeof(b) << endl;
return 0;
}
Template Scenario1
1)Define a function template “func_swap” that
swaps two values. The function takes two reference
arguments of type T. It then swaps the values. As the
arguments are references, whatever changes we do to
arguments in the function will be reflected in the
caller function.
Template Scenario2
• Write a C++ program for implementing the concept class
template. Create the template class myclass. Inside this, create a
constructor that will initialize the two members a and b of the
class. There is another member function getMaxval which is
also a function template that returns a maximum of a and b.In
the main function,construct two objects, myobject of type
integer and mychobject of type character. Then call the
getMaxval function on each of these objects to determine
maximum value.
• Note that apart from template type parameters (parameters of
type T), template functions can also have ordinary parameters
like normal functions and also default parameter values.
Direct Questions
1) C++ program to determine which triangle is greater
in term of area
2) C++ program to Display Largest Element of an arr
ay
3) C++ program to find Maximum or largest number i
n array
4) C++ program for ATM cash withdrawal/c++
program for ATM machine
Topic :Exceptional Handling: try and
catch, multilevel exceptional
Exceptions
• It Indicate problems that occur during a program’s
execution
• It is Occur infrequently
• Exceptions provide a way to transfer control from one
part of a program to another.
• A C++ exception is a response to an exceptional
circumstance that arises while a program is running,
such as an attempt to divide by zero.
Exception handling
• Can resolve exceptions
• Allow a program to continue executing or
• Notify the user of the problem and
• Terminate the program in a controlled manner
• Makes programs robust and fault-tolerant
• Types
• Synchronous exception (out-of-range index,
overflow)
• Asynchronous exception (keyboard interrupts)
Types of Exception
Two types of exception:
Synchronous Exceptions
Asynchronous Exceptions
Synchronous Exceptions
•Occur during the program execution due to some fault in the input
data or technique that is not suitable to handle the current class of
data, within the program .
•For example:
• errors such as out of range
• Overflow
• underflow and so on
Asynchronous Exceptions
•Caused by events or faults unrelated (external) to the program and
beyond the control of the program.
•For example
• errors such as keyboard interrupts
• hardware malfunctions
• disk failure and so on
• try
• catch
• throw
Simple Exceptions : syntax
……..
………
try
{
………
throw exception;
………
………
}
catch(type arg)
{
……….
………..
}
…….
…….
Exceptions
Simple Exceptions : Example
#include<iostream> else
using namespace std; {
int main() throw(b);
{ }
int a,b; }
cout<<"Enter the value of a and b"; catch(int i)
cin >> a>> b; {
try cout <<“Attempted to divide by zero!”;
{ }
if (b!=0) }
{
cout<<“result (a/b)=”<<a/b;
}
Nested try blocks
try
{
……..
try
{
………
}
catch (type arg)
{
………
}
}
catch(type arg)
{
……….
………..
}
Multiple Catch Exception
Note :
A better way to use this as a default statement along with
other catch statement so that it can catch all those exception
which are not handle by other catch statement
Multiple catch statement : Syntax
try
{
……..
}
catch (type1 arg)
{
………
}
catch (type2 arg)
{
………
}
……..
catch(typeN arg)
{
………..
}
Multiple Exceptions : Example
#include<iostream>
using namespace std; catch(int i)
int main()
{
{
int a,b; cout <<“exception caught : Division by zero”;
cin >> a>> b; }
try catch (char st)
{ {
if (b!=a) cout << “exception caught : Division is less
{ than 1”;
float div = (float) a/b; }
if(div <0)
throw ‘e’;
catch(…)
cout<<div; {
} cout << “Exception : unknown”;
else }
throw b; }
}
catch(int i)
{cout <<“exception caught”;
}
Bad Exception: Example
std::cerr:-
The object is declared in header <iostream> with external linkage and static duration: it
lasts the entire duration of the program.
// bad_exception example
#include <iostream> // std::cerr
#include <exception> // std::bad_exception, std::set_unexpected
void myunexpected () {
std::cerr << "unexpected handler called\n";
throw;
}
void myfunction () throw (int,std::bad_exception) {
throw 'x'; // throws char (not in exception-specification)
}
int main (void) { Output:-
std::set_unexpected (myunexpected); Unexpected handler called
try { Caught bad exception
myfunction();
}
catch (int) { std::cerr << "caught int\n"; }
catch (std::bad_exception be) { std::cerr << "caught bad_exception\n"; }
catch (...) { std::cerr << "caught some other exception\n"; }
return 0;
}
Bad Allocation: Example
Type of the exceptions thrown by the standard definitions of
operator new and operator new[] when they fail to allocate the
requested storage space.
int main () {
try
{
int * myarray = new int[1000000000000];
}
catch (std::bad_alloc & exception)
{
std::cerr << "bad_alloc detected: " << exception.what();
}
return 0;
}
https://www.sololearn.com/Play/CPlusPlus
https://www.hackerrank.com/domains/cpp
Topic :throw, throws and finally
throwing Exception
• When an exception is detected, it is thrown using
throw statement in the try block
• It is also possible, where we have nested try-catch
statement
throw;
• It cause the current exception to be thrown to the
next enclosing try/catch sequence and is caught by a
catch statement listed after that enclosing try block.
throwing Exception
Rethrowing Exception
The throw point
• Used to indicate that an exception has occurred
• It is called “throwing an exception”
• Throw normally specifies an operand:
• Will be caught by closest exception handler
The throw point Example
#include <iostream>
using namespace std;
int main() {
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;
}
return 0; }
Try with Multiple Catch Block
try {
// the protected code }
catch( Exception_Name exception1 ) {
// catch block }
catch( Exception_Name exception2 ) {
// catch block }
catch( Exception_Name exceptionN ) {
// catch block }
Try with Multiple Catch Block Example
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<int> vec;
vec.push_back(0);
vec.push_back(1);
// access the third element, which doesn't exist
try
{
vec.at(2);
}
catch (Exception i)
{ cout<<“Exception I caught”<<endl;}
try
{
// statements that may raise an exception
}
__finally
{
// statements that are called even
//if there is an exception in the try block
}
Example
else
#include<iostream> {
using namespace std; throw(b);
int main() }
{
}
int a,b;
cin >> a>> b; catch(int i)
try {
{ cout <<“exception caught”;
if (b!=0) }
{
__finally
cout<<“result (a/b)=”<<a/b;
} {
Cout<<“Division”;
}
}
Topic : Dynamic Modelling: Package
Diagram, UML Component Diagram
Dynamic Modelling
• Packages are depicted as file folders and can be used on any of the
UML diagrams.
Package Diagram: purpose
A structural relationship
2 Association describing a set of links
connected between objects.
Symbol and notation of Deployment diagram
Example
When to use Deployment Diagram