0% found this document useful (0 votes)
0 views25 pages

cpp_unit-V

Uploaded by

ranganadh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views25 pages

cpp_unit-V

Uploaded by

ranganadh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

UNIT-V
(Generic Programming with Templates & Exception Handling)

The template is one of the most useful characteristics of the C+


+. A few old compilers do not allow the template mechanism.
Templates are a part of ANSI C++ standard. All major compilers
support templates in their new versions.

In templates, generic data types are used as arguments, and they


can handle a variety of data types. A function that works for all
C++ data types is called a generic function. Templates help
the programmer declare groups of functions or classes. When
used with functions, they are called function templates. For
example, we can create a template for the function, square(). It
helps us calculate the square of a number of any data type,
including int, float, long, and double. The templates can be
associated with classes; such templates are called class
templates.

NEED FOR TEMPLATES


A template is a technique that allows a single function or class to
work with different data types. Using a template, we can create a
single function that can process any type of data; that is, the
formal arguments of a template function are of template
(generic) type. They can accept data of any type, such
as int, float, and long. Thus, a single function can be used to
accept values of a different data type.

Usually, we overload a function when we need to handle different


data types. This approach increases the program size. The
disadvantages are that not only the program length is increased
but also more local variables are created in the memory. A

P a g e 1 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

template safely overcomes all the limitations occurring during


the overloading function and allows better flexibility to the
program. The portability provided by a template mechanism can
be extended to classes.

DEFINITION OF CLASS TEMPLATES

In order to declare a class of template type, the following syntax


is used:

Template Declaration

template< class T>

classname_of_class

// class data member and function

The first statement template < class T> tells the compiler that
the following class declaration can use the template data type.
The T is a variable of template type that can be used in the class
to define a variable of template type.
Both template and class are keywords. The <> (angle bracket)
is used to declare the variables of template type that can be used
inside the class to define the variables of template type. One or
more variables can be declared separated by a comma.
Templates cannot be declared inside classes or functions. They
should be global and should not be local.

T k;

where, k is the variable of template type. Most of the authors


use T for defining a template; instead of T, we can use any
alphabet.
P a g e 2 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

Write a program to show values of different data types


using overloaded constructor.

#include<iostream.h>

#include<conio.h>

class data

public:

data(char c)

cout<<“\n”<< “ c=”<<c <<“ Size in bytes:”<<size of(c);

data(int c)

cout<<“\n”<< “ c=”<<c <<“ Size in bytes:”<<size of(c);

data(double c)

cout<<“\n”<< “ c=”<<c <<“ Size in bytes:”<<size of(c);}

};

void main()

clrscr();
P a g e 3 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

data h(‘A’); // passes character type data

datai(100); // passes integer type data

data j(68.2); // passes double type data

OUTPUT

c = A Size in bytes :1

c = 100 Size in bytes :2

c = 68.2 Size in bytes :8

Explanation: In the above program, the class data contains


three overloaded one-argument constructors. The constructor is
overloaded for char, int, and double type. In function main(),
three objects h, i, and j are created, and the values passed are
of different types. The values passed are char,
int, and double type. The compiler invokes different
constructors for various data types. Here, in order to manipulate
different data types, we require to overload the constructor; that
is, defining a separate function for each non-compatible data
type. This approach has the following disadvantages:

1. Re-defining the functions separately for each data type increases


the source code and requires more time.
2. The program size is increased. Hence, more disk space is occupied.
3. If the function contains a bug, it should be corrected in every
function.

NORMAL FUNCTION TEMPLATES

The difference between normal and member functions is that


normal functions are defined outside the class. They are not
P a g e 4 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

members of any class and, hence, can be invoked directly


without using the object of a dot operator. The member functions
are class members, and they can be invoked using the object of
the class they belong to.

In C++, normal functions are commonly used as in C. However,


the user who wants to use C++ as better C can utilize this
concept. The declaration of a normal template function can be
done in the following manner:

Normal Template Function Declaration

template< class T>

retuntypefunction_name (arguments )

// code

The following program shows the practical working of template


function:

Write a program to define normal template function.

#include<iostream.h>

#include<conio.h>

template<class T>

void show ( T x)

{cout<<“\n x=”<<x ;}

void main()

P a g e 5 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

clrscr();

char c=‘A’;

inti=65;

double d=65.254;

show(c);

show(i);

show(d);

OUTPUT

x=A

x=65

x=65.254

Explanation: Before the body of the function show(), the


template argument T is declared. The function show() has one
argument x of template type. As explained earlier, the template
type variable can accept all types of data. Thus, the normal
function show can be used to display values of different data
types. In main function, the show() functions are invoked
with char, int, and double type of values being passed. The
same is displayed in the output.

Write a program to define data members of template type.

#include<iostream.h>

#include<conio.h>

template<class T>

P a g e 6 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

class data

T x;

public:

data (T u) {x=u;}

void show (T y)

cout<<“ x=”<<x;

cout<<“ y=” <<y<<“\n”;

};

void main()

clrscr();

data<char> c(‘B’);

data<int>i(100);

data<double> d(48.25);

c.show(‘A’);

i.show(65);

d.show(68.25);

OUTPUT
P a g e 7 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

x=B y=A

x=100 y=65

x=48.25 y=68.25

Explanation: In this program, before the declaration of class


data, template <class T> is declared. This declaration allows the
entire class, including member function and data member, to use
the template-type argument. We have declared data member x of
template type. In addition, the one-argument constructor and
member function show() also have one formal argument of
template type.

Write a program to create square() function using


template.
#include<iostream.h>

#include<conio.h>

template<class S>

classsqr

public:

sqr (S c)

cout<<“\n”<< “ c=”<<c*c;

};
P a g e 8 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

void main()

clrscr();

sqr<int>i(25);

sqr<float> f(15.2);

OUTPUT

c = 625

c = 231.039993

Explanation: In the above program, the class sqr is declared.


It contains a constructor with one argument of template type.
In main() function, the object i indicates int type,
and f indicates floattype. The objects i and f invoke the
constructor sqr() with values 25 and 15.2, respectively. The
constructor displays the squares of these numbers.

OVERLOADING OF TEMPLATE FUNCTIONS

A template function also supports the overloading mechanism. It


can be overloaded by a normal function or a template function.
While invoking these functions, an error occurs if no accurate
match is met. No implicit conversion is carried out in the
parameters of template functions. The compiler observes the
following rules for choosing an appropriate function when the
program contains overloaded functions:

1. Searches for an accurate match of functions; if found, it is invoked


2. Searches for a template function through which a function that can
be invoked with an accurate match can be generated; if found, it is
invoked

P a g e 9 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

3. Attempts a normal overloading declaration for the function


4. In case no match is found, an error will be reported

Write a program to overload a template function.

#include<iostream.h>

#include<conio.h>

template<class A>

void show(A c)

cout<<“\n Template variable c=”<<c;

void show (int f)

cout<<“\n Integer variable f=”<<f;

void main()

clrscr();

show(‘C’);

show(50);

show(50.25);

return 0;

P a g e 10 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

OUTPUT

Template variable c = C

Integer variable f = 50

Template variable c = 50.25

BUBBLE SORT USING FUNCTION TEMPLATES


In application software, large amounts of data are manipulated
and sorting techniques are frequently used in such operations.
The sorting mechanism helps view the information in different
ways. The template function can also be used in the sorting
operation. The following program illustrates the use of the
template function with the bubble sorting method:

Write a program to sort integer and float array elements


using bubble sort method.

#include<iostream.h>

#include<conio.h>

template<class S>

voidb_sort ( S u[], int k)

for (int x=0;x<k-1;x++)

for (int y=k-1;x<y;y--)

if (u[y]<u[y-1]) // checks successive numbers

{
P a g e 11 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

S p;

p=u[y]; // assigns to temprary variable

u[y]=u[y-1]; // exchange of elements

u[y-1]=p; // collects from temporary variable

void main()

clrscr();

inti[5]={4,3,2,1,-4};

float f[5]={5.3,5.1,5.5,4.5,3.2};

b_sort(i,5); // call to function

b_sort(f,5); // call to function

int x=0,y=0;

cout<<“\nInteger array elements in ascending order:”;

while (x<5) cout<<i[x++] <<“ ”; // display contents of

// integer array

cout<<“\nFloat array elements in ascending order:”;

while ( y<5) cout<<f[y++] <<“ ”; // displays contents


of

// float array

P a g e 12 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

OUTPUT

Integer array elements in ascending order: -4 1 2 3 4

Float array elements in ascending order : 3.2 4.5 5.1 5.3


5.5

DIFFERENCES BETWEEN TEMPLATES AND MACROS

1. Macros are not type safe; that is, a macro defined for integer operations
cannot accept floatdata. They are expanded with no type checking.
2. It is difficult to find error in macros.
3. In case a variable is post-incremented or decremented, the operation is
carried out twice.

Consider the following macro:

# define max(a) a + ++a

void main()

int a=10, c;

c=max(a);

cout<<c;

Write a program to increment the value of a variable


using template.

#include<iostream.h>

#include<conio.h>

template<class T>
P a g e 13 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

T max(T k)

++k;

return k;

void main()

clrscr();

int a=10, c;

c=max(a);

cout<<c;

OUTPUT

11

Exception Handling

While writing large programs, a programmer usually makes


many mistakes. Due to this, bugs occur even in the released
softwares. Developing an error-free program is the only objective
and intention of the programmer. Programmers should take care
to prevent errors. Errors can be trapped using exception-
handling features.

A few languages support exception-handling features. Without


this feature, the programmers should find out errors on their
own. The errors may be logical errors or syntactic mistakes
(syntax mistakes). The logical error remains in the program due
P a g e 14 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

to a poor understanding of the program. The syntax mistakes


made are due to a lack of understanding of the programming
language. C++ provides an exception-handling procedure to
reduce the errors that the programmer makes.

The programmer always faces unusual errors while writing


programs. An exception is an abnormal termination of the
program, which is executed in a program at run time or it may be
called at run time when the error occurs. The exception contains
warning messages such as invalid argument, insufficient
memory, and division by zero. ANSI C++ is built in language
functions for trapping errors and controlling exceptions. All C++
compilers support this newly added facility.

PRINCIPLES OF EXCEPTION HANDLING

Similar to errors, exceptions are also of two types. They are as


follows:

 Synchronous exceptions
 Asynchronous exceptions

C++ has a well-organized, object-oriented method to control run-


time errors that occur in the program. The goal of exception
handling is to create a routine that detects and sends an
exceptional condition in order to execute suitable actions. The
routine needs to carry out the following responsibilities:

1. Detect the problem


2. Warn that an error has been detected
3. Accept the error message
4. Perform accurate actions without troubling the user

An exception is an object. It is sent from the part of the program


where an error occurs to the part of the program that is going to
control the error. An exception provides an explicit pathway that
contains errors to the code which controls these errors.

P a g e 15 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

THE KEYWORDS TRY, THROW, AND CATCH

The exception-handling technique passes the control of a


program from a location of exception in a program to an
exception-handler routine linked with the try block. An
exception-handler routine can only be called by
the throw statement.

try: The try keyword is followed by a series of statements enclosed in curly


braces.

Syntax of try statement

try

statement 1;

statement 2;

throw: The function of the throw statement is to send the


exception found. The declaration of the throw statement is as
follows:

Syntax of throw statement

throw (excep);

throw excep;

throw // re-throwing of an exception

P a g e 16 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

The argument excep is allowed to be of any type, and it may be a


constant. The catch block associated with the try block catches
the exception thrown. The control is transferred from
the tryblock to the catch block. The throw statement can be
placed in a function or is a nested loop, but it should be in
the try block. After throwing the exception, control passes to
the catch statement.

catch: Similar to the try block, the catch block also contains a
series of statements enclosed in curly braces. It also contains an
argument of an exception type in parentheses.

Syntax of catch statement

try

Statement 1;

Statement 2;

catch ( argument)

statement 3; // Action to be taken

When an exception is found, the catch block is executed.


The catch statement contains an argument of exception type,
and it is optional. When an argument is declared, the argument
can be used in the catch block. After the execution of
the catch block, the statements inside the blocks are executed.

P a g e 17 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

In case no exception is caught, the catch block is ignored, and if


a mismatch is found, the program is terminated.

Write a program to throw exception when j=1 otherwise


perform the subtraction of x and y.

#include<iostream.h>

#include<conio.h>

void main()

Clrscr();

intx,y;

cout<<“\n Enter values of x and y\n”;

cin>>x>>y;

int j;

j=x>y ?0 :1;

try

if (j==0)

{ cout<<“Subtraction (x-y)=”<<x-y<<“\n”; }

else { throw(j); }

catch (int k)

P a g e 18 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

cout<<“Exception caught : j =”<<j <<“\n”;

OUTPUT

Enter values of x and y

78

Exception caught : j = 1

Enter values of x and y

48

Exception caught : j = 1

MULTIPLE CATCH STATEMENTS

We can also define multiple catch blocks; in the try block, such
programs also contain multiple throw statements based on
certain conditions. The format of multiple catch statements is as
follows:

try

// try section

catch (object1)

P a g e 19 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

// catch section1

catch (object2)

// catch section2

.......

.......

catch (type n object)

// catch section-n

Write a program to throw multiple exceptions and define


multiple catchstatement.

#include<iostream.h>

#include<conio.h>

Void num (int k)

try

{
P a g e 20 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

if (k==0) throw k;

else

if (k>0) throw ‘P’;

else

if (k<0) throw .0;

cout<<“*** try block ***\n”;

catch(char g)

cout<<“Caught a positive value \n”;

catch (int j)

cout<<“caught an null value \n”;

catch (double f)

cout<<“Caught a Negative value \n”;

cout<<“*** try catch ***\n \n”;

void main()
P a g e 21 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

Clrscr();

cout<<“Demo of Multiple catches\n”;

num(0);

num(5);

num(-1);

return 0;

OUTPUT

Demo of Multiple catches

caught an null value

*** try catch ***

Caught a positive value

*** try catch ***

Caught a Negative value

*** try catch ***

SPECIFYING EXCEPTIONS

The specified exceptions are used when we want to bind the


function to throw only specified exceptions. Specific exception is
thrown using condition statement and list of data items in throw.
The format for such exceptions is as given below:

Specifying Exceptions

P a g e 22 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

Data-type fucntion_name (parameter list) throw (data


type list)

Statement 1;

Statement 2; Function definition

statement 3;

Write a program to restrict a function to throw only


specified type of exceptions.

#include<iostream>

#include<conio.h>

void check (int k) throw (int,double)

if (k==1) throw ‘k’;

else

if (k==2) throw k;

else

if (k==-2) throw 1.0;

cout<<“\n End of function check()”;

void main()

P a g e 23 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

Clrscr();

try {

cout<<“k==1\n”;

check(1);

cout<<“k==2\n”;

check(2);

cout<<“k==-2\n”;

check(-2);

cout<<“k==3\n”;

check(3);

catch ( char g)

cout<<“Caught a character exception \n”;

catch (int j)

cout<<“Caught a character exception \n”;

catch (double s)

cout<<“Caught a double exception \n”;


P a g e 24 | 25 (Ranganadh.G)
OBJECT-ORIENTED PROGRAMMING THROUGH C++(R16)

cout<<“\n End of main()”;

OUTPUT

k==1

Caught a character exception

End of main() Press any k

ASSIGNMENT

1. Explain the Definition of class Templates and need for


Template.
2. Explain an introduction to Generic Programming with
templates.
3. Explain the Normal Function Templates with an
example.
4. Write a program on Bubble Sort using Function
Templates.
5. Explain the difference between Templates and Macros.
6. What is Exception Handling. Explain its principles.
7. Explain the key words try, throw and catch with an
example.
8. Write a note on Multiple catch Statements with an
example.

P a g e 25 | 25 (Ranganadh.G)

You might also like