OODP Unit 4
OODP Unit 4
Unit 4 Generic
- Templates: Introduction
2. Class templates
Function templates
• In Function template, a single function works with different data types.
• But a standard function works only with one set of data types.
• i.e. Generic functions template define a set of operations that can be applied to the various
types of data.
• The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
• Example , if we have an add() function, we can create versions of the add function
for adding the int, float or double type values
o Syntax
int main() {
cout<<"Integer sum is "<<add(5, 6)<<endl;
2
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
cout<<"float sum is "<<add(5.3, 2.6)<<endl;
return 0;
}
Output: Integer
sum is 11
float sum is 7.9
#include <iostream>
#include <string>
using namespace std;
3
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
template <class T> void
display(T num)
{ cout<<num<<endl; }
int main()
{
display(20); display(12.34,1234); return 0; }
Rules to select suitable template
• When the compiler encounters an overloaded template function, it uses the following
rules to select a suitable template.
• If an exact match is found using an ordinary function, the compiler calls it.
• If an exact match is not found, it looks for a function template from which an exact match
can be generated, if found, it calls for the same.
• If no match is found, ordinary overloading resolution for the function is tried.
• If no match is still found, an error is generated.
• If more than one match is found, then an ambiguity error is generated.
Class Templates
• A class template specify how individual classes can be constructed that supports similar
operations for different data types.
• When a class uses the concept of Template, then the class is known as
generic class.
•
• Therefore, templates enable programmers to create abstract classes that define the
behavior of the class without actually knowing what data type will be handled by the
class operations.
4
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
• The template class is prefixed with template <class Type> that tells the compiler that a
template is being declared.
• The Syntax for declaring a class template is template <class Type1, class Type2, ……>
class class_name
5
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
}; int
main() {
Calculator <int> obj1(2, 1);
Calculator <float> obj2(2.4, 1.2);
cout << "Int results:" << endl; obj1.displayResult(); cout
<< endl << "Float results:" << endl; obj2.displayResult();
return 0;
}
Output:
Int results:
Numbers: 2 and 1.
2+1=3
2-1=1
2*1=2
2/1=2
Float results:
Numbers: 2.4 and 1.2.
2.4 + 1.2 = 3.6
2.4 - 1.2 = 1.2
2.4 * 1.2 = 2.88
2.4 / 1.2 = 2
6
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
Class Template Function Template
A class template is used when we want to Function template is used when we want to
create a class that is parameterised by a create a function that can operate on many
type, several functions defined in the same different types. One function operates on
class template work on different data type. many different data type.
A class template can have default template Function templates can’t have default
parameters template parameters
A class template can be partially Function templates can’t be partially
specialized while classes can specialized
Write Example template class Program Write Example template function Program
Exception
• Exceptions are runtime anomalies or unusual conditions such as divide by zero, accessing
array out its bound, running out of memory or disk space, overflow and underflow that a
program may encounter during execution.
• Exceptions can be categorized as synchronous and asynchronous.
• Synchronous Exceptions like divide by zero, array index out of bound etc can be
controlled by the program.
• Asynchronous Exceptions like an interrupt from the keyboard, hardware malfunction and
disk failure are caused by events that are beyond the control of the program.
#include <iostream>
using namespace std;
int main() {
float a,b;
cout<<"Enter any two integer values";
cin>>a>>b;
try { if(b!
=0)
{ cout<<"Result(a/b)="<<a/b<<endl; }
else
{ throw b; }
}
catch(float ex)
{
cout<<"Exception caught:Divide By Zero \n";
}
}
Exceptional Handling: Multilevel exceptional - multiple catch
• It is possible to associate more than one catch statement with a single try block.
• This is usually done when a program segment has more than one condition to throw as an
exception.
• In such cases, when an exception is thrown, the exception handlers are searched to find an
appropriate match.
• Then, the first matched catch block is executed. After execution, the program control goes
to the first statement after the last catch block for that try block. This means that all other
catch blocks are ignored.
• However, if no match is found, then the program is terminated using the default abort ().
Syntax for multiple catch
try
{ //try block }
catch(data type1
arg) { //catch
block1 } catch(data
8
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
type2 arg) { //catch
block2 }
………………
……………..
catch(data typeN arg)
{ //catch blockN }
catch (int x)
{ cout << "Catch a integer and that integer is positive:" << x<<endl; }
catch (char x)
{ cout << "Catch a integer and that integer is negative:" << x<<endl; }
int main() {
cout << "Testing multiple catches\n";
test(10); test(-100);
test(0);
return 0;
}
Output:
Testing multiple catches
Catch a integer and that integer is positive:10
Catch a integer and that integer is negative:N
Catch a integer and that integer is:zero
9
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
Catch All Exceptions or Default Exception Handling
• The catch-all clause, catch (...) matches exceptions of any type.
• If present, it has to be the last catch clause in the handler-seq.
• Catch-all block may be used to catch every possible exception thrown from the try block.
int main() {
int var = 0;
try
{
if (var == 0)
{ throw var; }
}
catch (float ex) {
// Code executed when exception Catch with float type
cout << "Float Exception catch : Value :" << ex;
}
catch (...) {
// Code executed when exception Catch : for default
cout << "Default Exception Catch";
}
return 0;
}
Output : Default Exception Catch
(Note : since no float type exception, default exception is executed)
Rethrowing Exception:
• In some situation, the exception handler in the catch block may decide to rethrow the
exception without processing it.
• If a catch block cannot handle the particular exception it has caught, it can rethrow the
exception.
• Syntax to rethrow the exception is throw;
• A throw statement without any exception explicitly mentioned causes the current
exception to be thrown to the next try catch block.
int main() {
11
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
• If a Function doesn’t handle the exception, the program stack unwinds the stack and
control returns to main(). But there’s no exception handler here either in main, then
main() terminates. At this point, we just terminated our application!
return 0;
}
Output 1: Enter a number: -5 terminate called after
throwing an instance of 'char const*' Output 2:
Enter a number: 5
The sqrt of 5 is 2.23607
Standard Exception
C++ provides a list of standard exceptions defined in <exception> which we can use in our
programs. These are arranged in a parent-child class hierarchy shown below –
12
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
Description of each exception mentioned in the above hierarchy are
13
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
10 This can be thrown by the 'at' method, for example a
std::out_of_range
std::vector and std::bitset<>::operator[]().
11 std::runtime_error An exception that theoretically cannot be detected by
reading the code.
12 std::overflow_error This is thrown if a mathematical overflow occurs.
13 std::range_error This is occurred when you try to store a value which is
out of range.
14 std::underflow_error This is thrown if a mathematical underflow occurs.
The exception class has a public virtual function called what() that returns a string that
explains the error.
Example program for Standard Exception
#include <iostream>
#include <exception> using namespace std;
int main() {
try
{ int *arr = new int[1000000000000000000000000000000000000000000000];
cout<<"memory allocated"; }
Both throw and throws are concepts of exception handling. The throws keyword is used to
declare which exceptions can be thrown from a method, while the throw keyword is used to
explicitly throw an exception within a method or block of code.
15
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
• A package is rendered as a tabbed folder - a rectangle with a small tab attached to the left
side of the top of the rectangle. If the members of the package are not shown inside the
package rectangle, then the name of the package should be placed inside.
Package org.hibernate
• The members of the package may be shown within the boundaries of the package. In this
case the name of the package should be placed on the tab.
• A diagram showing a package with content is allowed to show only a subset of the
contained elements according to some criterion.
• Members of the package may be shown outside of the package by branching lines from
the package to the members. A plus sign (+) within a circle is drawn at the end attached to
the namespace (package). This notation for packages is semantically equivalent to
composition (which is shown using solid diamond.)
• Owned and imported elements may have a visibility that determines whether they are
available outside the package.
• If an element that is owned by a package has visibility, it could be only public or private
visibility. Protected or package visibility is not allowed. The visibility of a package
element may be indicated by preceding the name of the element by a visibility symbol
("+" for public and "-" for private).
16
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
• Package Diagram - Dependency Notation : There are two sub-types involved in
dependency.
• They are <<import>> & <<access>>.
• <<import>> - one package imports the functionality of other package.
• <<access>> - one package requires help from functions of other package.
Some major elements of the package diagram are shown on the drawing below. Web
Shopping, Mobile Shopping, Phone Shopping, and Mail Shopping packages merge
Shopping Cart package. The same 4 packages use Payment package. Both Payment and
Shopping Cart packages import other packages.
Implementation Diagram
• It shows the implementation phase of systems development, such as the source code
structure and the run-time implementation structure.
• There are two types of implementation diagrams:
o component diagrams show the structure of the code itself, o and
deployment diagrams show the structure of the runtime system
17
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
• It model the physical components(such as source code, executable program, user
interface, libraries,dll’s) in a design.
• Component diagrams can also be described as a static implementation view of a system.
• Static implementation represents the organization of the components at a particular
moment.
• A single component diagram cannot represent the entire system but a collection of
diagrams is used to represent the whole.
• Purpose of Component Diagrams o Visualize the components of a system. o Construct
executables by using forward and reverse engineering.
o Describe the organization and relationships of the components.
• Component diagrams are used during the implementation phase of an application.
However, it is prepared well in advance to visualize the implementation details.
• Before drawing a component diagram, the following artifacts are to be identified clearly
1. Files used in the system.
2. Libraries and other artifacts relevant to the application.
3. Relationships among the artifacts.
2. Interface: The Interface is a named set of public features . There are two types of
Interfaces in Component Diagram: 1. Provided interfaces 2. Required interfaces.
An interface (semi-circle on a stick) describes a group of operations used
(required) or created by components. A full circle represents an interface created
or provided by the component.
18
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
4. Port: Ports are represented using a square along the edge of the system or a
component. A port is often used to help expose required and provided interfaces
of a component.
5. Node: Represents hardware or software objects, which are of a higher level than
components.
19
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
UML Deployment Diagram
• Deployment diagram is a type of UML structure diagram
• Deployment diagram represents or describe the static deployment view of a system.
• It specifies the physical hardware on which the software system will execute.
• It also determines how the software is deployed on the underlying hardware.
• It maps software pieces of a system to the device that are going to execute it.
• In most cases, component diagrams are used in conjunction with deployment diagrams to
show how physical modules of code are distributed on various h/w platform.
• In many cases, component and deployment can be combined. Where Component
diagrams are used to describe the components and deployment diagrams shows how they
are deployed in hardware.
• Deployment diagram show the configuration of run-time processing elements and the
software components, processes, and objects that live in them.
• Software component instances represent run-time manifestations of code units.
• Before drawing a deployment diagram, the following artifacts should be identified.
o Nodes
o Relationships among nodes Deployment diagram
elements:
• A variety of shapes make up deployment diagrams.
• Artifact: A product developed by the software, symbolized by a rectangle with the name
and the word “artifact” enclosed by double arrows.
• Communication path: A straight line that represents communication between two device
nodes.
• Package: A file-shaped box that groups together all the device nodes to encapsulate the
entire deployment.
• Component: An entity required to execute a stereotype function. Take a look at this guide
for UML component notation.
• Node: A hardware or software object, shown by a three-dimensional box. Example
20
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST
• Once the installation and the registration are done, iTunes application can easily
interconnect with the Apple iTunes store.
• Users can purchase and download music, video, TV serials, etc. and cache it in the media
library.
• Devices like Apple iPod Touch and Apple iPhone can update its own media library from
the computer with iTunes with the help of USB or simply by downloading media directly
from the Apple iTunes store using wireless protocols, for example; Wi-Fi, 3G, or EDGE.
21
Prepared by Dr J Faritha Banu, Assistant Professor/ SRMIST