Research Methodolgy & Intellectual Property Rights Series 1
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Templates by Dr MK Jayanthi Kannan.pdf
1. Course Code CSE2001
Object Oriented Programming with C++
Type LTP
Credits 4
UNIT 4 : Exception handling
and Templates
2. Object Oriented Programming with C++
Course Code: CSE2001
UNIT 4 : Exception handling and Templates
UNIT 4 :Exception handling and Templates
4.1 Exception handling (user-defined exception)
4.2 Function template ,
4.3 Class template
4.4 Template with inheritance ,
4.5 STL
4.6 Container,
4.7 Algorithm,
4.8 Iterator vector, list, stack, map
3. C++ Exceptions
•When executing C++ code, different errors can
occur:
•coding errors made by the programmer, errors due
to wrong input, or other unforeseeable things.
•When an error occurs, C++ will normally stop and
generate an error message.
•The technical term for this is: C++ will throw
an exception (throw an error).
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
4. C++ try and catch
• Exception handling in C++ consist of three
keywords: try, throw and catch:
• The try statement allows you to define a block
of code to be tested for errors while it is being
executed.
• The throw keyword throws an exception when a
problem is detected, which lets us create a custom
error.
• The catch statement allows you to define a block
of code to be executed, if an error occurs in the
try block.
• The try and catch keywords come in pairs:
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
5. C++ try and catch
SYNTAX
try
{
// Block of code to try
throw exception;
// Throw an exception when a problem arise
}
catch ()
{
// Block of code to handle errors
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
6. Example
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are not old
enough to vote.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18
years old.n";
cout << "Age is: " << myNum;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
7. • Example explained:
We use the try block to test some code:
If the age variable is less than 18, we will throw an
exception, and handle it in our catch block.
• In the catch block, we catch the error and do
something about it. The catch statement takes
a parameter:
in our example we use an int variable (myNum)
(because we are throwing an exception of int type
in the try block (age)), to output the value of age.
• If no error occurs (e.g. if age is 20 instead of 15,
meaning it will be be greater than 18),
the catch block is skipped:
Example
int age = 20;
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
8. You can also use the throw keyword to output a reference number, like a custom
error number/code for organizing purposes
• try
{
int age = 15;
if (age >= 18)
{
cout << "Access granted - you are old enough.";
} else
{
throw 505;
}
}
catch (int myNum)
{
cout << "Access denied - You must be at least 18
years old.n";
cout << "Error number: " << myNum;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
9. try
{
int age = 15;
if (age >= 18)
{
cout << "Access granted - you are old enough.";
} else
{
throw 505;
}
}
catch (...)
{
cout << "Access denied - You must be at least 18
years old.n";
}
Handle Any Type of Exceptions (...)
If you do not know the throw type used in the try block, you can use
the "three dots" syntax (...) inside the catch block, which will handle
any type of exception:
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
10.
11. Exceptions
• Exceptions are events that can modify the flow or control
through a program.
• They are automatically triggered on errors.
• try/except : catch and recover from raised by you or
Python exceptions
• try/finally: perform cleanup actions whether exceptions
occur or not
• raise: trigger an exception manually in your code
• assert: conditionally trigger an exception in your code
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
12. Exception Roles
• Error handling
– Wherever Python detects an error it raises exceptions
– Default behavior: stops program.
– Otherwise, code try to catch and recover from the exception (try
handler)
• Event notification
– Can signal a valid condition (for example, in search)
• Special-case handling
– Handles unusual situations
• Termination actions
– Guarantees the required closing-time operators (try/finally)
• Unusual control-flows
– A sort of high-level “goto”
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
13. Object Oriented Programming with C++
Course Code: CSE2001
UNIT 4 : Exception handling and Templates
UNIT 4 :Exception handling and Templates
4.1 Exception handling (user-defined exception)
4.2 Function template ,
4.3 Class template
4.4 Template with inheritance ,
4.5 STL
4.6 Container,
4.7 Algorithm,
4.8 Iterator vector, list, stack, map
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
14. Templates in C++:
• Templates are primarily implemented for crafting a family of classes or
functions having similar features.
• For example, a class template for an array of the class would create an
array having various data types such as float array and char array.
• Similarly, you can define a template for a function that helps you to
create multiple versions of the same function for a specific purpose.
• A template can be considered as a type of macro;
• When a particular type of object is defined for use, then the template
definition for that class is substituted with the required data type.
• A template can be considered a formula or blueprint for generic class or
function creations.
• It allows a function or class to work on different data types without
rewriting them.
Templates can be of two types in C++:
•Function templates
•Class templates
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
15. 4.2 Function template ,
• A function template defines a family of
functions.
• Templates are one of the most prominent
examples of reuse concept in action.
• It supports the idea of generic programming by
providing facility for defining generic classes
and functions.
• Thus a template class provides a broad
architecture which can be used to create a
number of new classes.
• Similarly, a template function can be used to
write various versions of the function.
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
16. 4.2 FUNCTION TEMPLATES
• Function templates create a generic function type.
• This generic function can then be used to create a family of
functions that may take different arguments.
• A function template can be defined as follows
template<classT>
return_typefunction_name(argumentsoftypeT)
{
………..
……….bodyoffunctionwithargumentoftypeT
………..
}; Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
17. Template<classT>
voidswap(T & x,T& y)
{
Ttemp=x;
x = y;
y= temp:
};
Functiontemplates areanother wayof handlingoverloadedfunctionrequirements. If
overloadedfunctions performidenticaloperations for different typeof data thenthey
can be more appropriately and conveniently declared as function templates.The
following example demonstrates creation of a function template swap:
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
19. #include<iostream.h>
#include<conio.h>
template<class T>
void swap(T &i, T &j)
{
T t;
t=i;
i=j;
j=t;
}
int main()
{ int e,f;
char g,r;
float x,y;
cout<<"n Please insert 2 Integer Values:"; cin>>e>>f;
swap(e,f);
cout<<"n Integer values after Swapping:";
cout<<e<<"t"<<f<<"nn";
cout<<"n Please insert 2 Character Values:"; cin>>g>>r;
swap(g,r);
cout<<"n Character Values after Swapping:";
cout<<g<<"t"<<r<<"nn";
cout<<"n please insert 2 Float Values:"; cin>>x>>y;
swap(x,y);
cout<<"n The resultatnt float values after swapping:";
cout<<x<<"t"<<y<<"nn";
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
20. Please insert 2 Integer Values: 12 10
Integer values after Swapping: 10 12
Please insert 2 Character Values: A B
Character Values after Swapping: B A
Please insert 2 Float Values: 1.1 2.1
The resultatnt float values after swapping: 2.1 1.1
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
21. //Write a C++ Program using Function Template to sort a list in desired order
//using function templates swap() and bsort() as shown in the rogram below:
#include <iostream>
template<class T>
void bsort(T a[], int n)
{
for (int i=0; i<n-1; i++)
for (int j=n-1; i<j; j--)
if (a[j] < a[j-1])
swap(a[j], a[j-1]);
}
template <class X>
void swap( X &a, X &b)
{
X temp =a;
a = b;
b = temp;
}
int main()
{
int x[5] = {10,50,30,60,40};
float y[5] = {3.2, 71.5, 17.3, 45.9, 92.7};
bsort(x,5);
bsort(y,5);
cout << “Sorted X-Array:”;
for (int i=0; i<5; i++)
cout << x[i] << “ ”;
cout << endl;
cout << “Sorted Y-Array:”;
for (int j=0; j<5; j++)
cout << y[j] << “ ”;
cout << endl;
return(0);
};
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
22. //Write a C++ Program using Function Template to sort a list in desired order using
//function templates swap() and bsort() as shown in the rogram below:
#include <iostream>
template<class T>
void bsort(T a[], int n)
{
for (int i=0; i<n-1; i++)
for (int j=n-1; i<j; j--)
if (a[j] < a[j-1])
swap(a[j], a[j-1]);
}
template <class X>
void swap( X &a, X &b)
{
X temp =a;
a = b;
b = temp;
}
int main()
{
int x[5] = {10,50,30,60,40};
float y[5] = {3.2, 71.5, 17.3, 45.9, 92.7};
bsort(x,5);
bsort(y,5);
cout << “Sorted X-Array:”;
for (int i=0; i<5; i++)
cout << x[i] << “ ”;
cout << endl;
cout << “Sorted Y-Array:”;
for (int j=0; j<5; j++)
cout << y[j] << “ ”;
cout << endl;
return(0);
};
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
23. • This program uses two function templates swap()
and bsort().
• The function template swap() is invoked within the
bsort() function and is hence said to be nested in it.
• This program can be used to sort different types of
lists without the need of modifying the program.
• The program will produce following output:
• Sorted X-Array: 10 30 40 50 60
• Sorted Y-Array: 3.2 17.3 45.9 71.5 92.7
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
24. FUNCTION TEMPLATES
Function templates in C++ allow writing generic functions
that can operate with any data type.
They provide a way to define a single function that can
work with different types of parameters.
This feature promotes code reusability and flexibility.
Advantages of Function Templates:
Code Reusability: Function templates enable writing
generic code that can be used with different data types,
reducing code duplication and promoting reuse.
Flexibility: Templates allow functions to be parameterized
with different types, providing flexibility and supporting a
wide range of use cases.
Type Safety: Function templates support strong type
checking at compile time, ensuring type safety and
reducing runtime errors.
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
25. Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
26. FUNCTION TEMPLATES
Disadvantages of Function Templates:
Compilation Time: Function templates can increase
compilation time, especially for complex code, as the
compiler generates code for each specific
instantiation of the template.
Readability: Complex template code can be difficult
to read and understand, especially for developers
who are not familiar with template programming.
Code Bloat: Using function templates extensively
with many different types can lead to code bloat,
increasing the size of the compiled binary.
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
28. // C++ Program to demonstrate
// Use of template
#include <iostream>
using namespace std;
// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
template <typename T> T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{ // Call myMax for int
cout << myMax<int>(3, 7) << endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0) << endl;
// call myMax for char
cout << myMax<char>('g', 'e') << endl;
return 0;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
29. // C++ Program to demonstrate Use of template
#include <iostream>
using namespace std;
template <typename T>
T myMax(T x, T y)
{ return (x > y) ? x : y;
}
int main()
{ // Call myMax for int
cout << myMax<int>(3, 7) << endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0) << endl;
// call myMax for char
cout << myMax<char>('g', 'e') << endl;
return 0;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
30. #include <iostream>
using namespace std;
// Function template to find the maximum of two values
template<typename T>
T max(T a, T b)
{
return (a > b) ? a : b;
}
int main()
{ // Call max function with different data types
cout << "Maximum of 5 and 3: " << max(5, 3) << endl;
// int
cout << "Maximum of 5.5 and 3.3: " << max(5.5, 3.3) <<
endl; // double
cout << "Maximum of 'a' and 'b': " << max('a', 'b') << endl;
// char
return 0;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
31. ; }
#include <iostream>
using namespace std;
// Function template to find the maximum of two values
template<typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
// Call max function with different data types
cout << "Maximum of 5 and 3: " << max(5, 3) << endl; // int
cout << "Maximum of 5.5 and 3.3: " << max(5.5, 3.3) << endl; // double
cout << "Maximum of 'a' and 'b': " << max('a', 'b') << endl; // char
return 0;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
32. // Implementing Bubble Sort using templates in C++
// A template function to implement bubble sort. // We can use this for any data type that
supports comparison operator < and swap works for it.
// C++ Program to implement Bubble sort using template function
#include <iostream>
using namespace std;
template <class T> void bubbleSort(T a[], int n)
{
for (int i = 0; i < n - 1; i++)
for (int j = n - 1; i < j; j--)
if (a[j] < a[j - 1])
swap(a[j], a[j - 1]);
}
int main()
{
int a[5] = { 10, 50, 30, 40, 20 };
int n = sizeof(a) / sizeof(a[0]);
// calls template function
bubbleSort<int>(a, n);
cout << " Sorted array : ";
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
Output
Sorted array : 10 20 30 40 50
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
33. Object Oriented Programming with C++
Course Code: CSE2001
UNIT 4 : Exception handling and Templates
UNIT 4 :Exception handling and Templates
4.1 Exception handling (user-defined exception)
4.2 Function template,
4.3 Class template
4.4 Template with inheritance,
4.5 STL
4.6 Container,
4.7 Algorithm,
4.8 Iterator vector, list, stack, map
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
34. 4.3 Class template
A class template defines a family of classes.
Syntax:
template < parameter-list > class-declaration
Example:
export template < parameter-list > class-declaration
Where a class declaration is the class name that
became the template name, and the parameter list is a
non-empty comma-separated list of the template
parameters.
A class template by itself is not a type, an object, or any other entity.
No code is generated from a source file that contains only template
definitions. This is the syntax for explicit instantiation is:
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
35. template class name < argument-list >;
// Explicit instantiation definition
extern template class name < argument-list > ;//
Explicit instantiation declaration
Class Templates
Class templates are useful when a class defines something
that is independent of the data type.
Can be useful for classes like LinkedList, BinaryTree, Stack,
Queue, Array, etc.
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
36. Overloading of Templates:
extern template class name < argument-list >;// Explicit instantiation
declaration
A template function may be overloaded either by the template function or by
ordinary functions of its name. In such programming cases, the overloading
resolution is accomplished as follows:
• Call a standard function that has an exact match
• A template function is called that could be created with an exact match
• Try normal overloading resolution to standard functions and call the one
that matches
Disadvantages of FT:
• Some compilers have poor support for templates.
• Many compilers lack clear instructions when they detect errors in the
definition of the template.
• Many compilers do not support the nesting of templates.
• When templates are used, all codes get exposed.
• The templates are in the header, where the complete rebuild of all project
pieces is required when the changes occur.
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
37. USE OF TEMPLATES
• The concept of class templates and function templates
derives its motivation from the principle of reuse.
• Rather than defining multiple classes and functions, we
define a generic type and depending on the kind of input
data it may customize itself.
• Templates in this sense serve as a blueprint for defining
classes and functions.
• This not only eliminates code duplication for handling
different data types but also makes the program
development easier and more manageable.
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
38. Class Templates
#include <iostream>
using namespace std;
// Class template for a generic Pair
template<typename T>
class Pair {
private:
T first;
T second;
public:
// Constructor
Pair(T f, T s) : first(f), second(s) {}
// Method to get the first element
T getFirst() const {
return first;
}
// Method to get the second element
T getSecond() const {
return second;
}
};
int main() {
// Create a Pair of integers
Pair<int> intPair(5, 10);
cout << "First: " << intPair.getFirst() << ", Second: " << intPair.getSecond() <<
endl;
// Create a Pair of doubles
Pair<double> doublePair(3.14, 6.28);
cout << "First: " << doublePair.getFirst() << ", Second: " <<
doublePair.getSecond() << endl;
return 0;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
39. #include <iostream>
using namespace std;
// Class template for a generic Pair
template<typename T>
class Pair
{
private:
T first;
T second;
public:
// Constructor
Pair(T f, T s) : first(f), second(s) {}
// Method to get the first element
T getFirst() const {
return first;
}
// Method to get the second element
T getSecond() const {
return second;
}
};
int main()
{
// Create a Pair of integers
Pair<int> intPair(5, 10);
cout << "First: " << intPair.getFirst() << ",
Second: " << intPair.getSecond() << endl;
// Create a Pair of doubles
Pair<double> doublePair(3.14, 6.28);
cout << "First: " << doublePair.getFirst() << ",
Second: " << doublePair.getSecond() << endl;
return 0;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
40. #include <iostream>
using namespace std;
// Class template for a generic Pair
template<typename T>
class Pair
{
private:
T first;
T second;
public:
// Constructor
Pair(T f, T s) : first(f), second(s) {}
// Method to get the first element
T getFirst() const {
return first;
}
// Method to get the second element
T getSecond() const {
return second;
}
};
int main()
{
// Create a Pair of integers
Pair<int> intobj1(5, 10);
cout << "First: " << intobj1.getFirst() << ",
Second: " << intobj1.getSecond() << endl;
// Create a Pair of doubles
Pair<double> doubleobj2(3.14, 6.28);
cout << "First: " << doubleobj2.getFirst() << ",
Second: " << doubleobjj2.getSecond() << endl;
return 0;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
41. template definition for a Vector class:
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
42. classname<type>objectname(argument list);
For example, followingstatements createclasses of 20element integer andfloat
vectors, respectively.
vector <int>v(20);
vector <float> v(20);
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
43. #include <iostream>
template<class T1, class T2>
class Example
{
T1 x; T2 y;
Public:
Example(T1 a, T2 b)
{
x = a; y = b;
}
void show ()
{
cout << x << “and” << y << “n”;
}
};
int main()
{
Example <float, int> test1 (3.45, 345);
Example <int, char> test2 (100, „m‟);
test1.show();
test2.show();
return(0);
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
44. #include <iostream>
template<class T1, class T2>
class Example
{
T1 x; T2 y;
Public:
Example(T1 a, T2 b)
{
x = a; y = b;
}
void show ()
{
cout << x << “and” << y << “n”;
}
};
int main()
{
Example <float, int> obj1(3.45, 345);
Example <int, char> obj2(100, „m‟);
obj1.show();
obj2.show();
return(0);
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
45. Class Templates:
• The program creates two template classes test1 and test2
using the template class Example.
• The test1 class has two parameter values “3.45” and “345”,
• whereas test2 class has two parameter values “100” and
character “m”.
• For creating test1 object, arguments are float and integer
respectively, whereas in case of test2 object they are integer
and character.
• The values displayed in invocation of show() function from
main will be “3.45 and 345” for test1 and “100 and m” for test2
object.
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
46. // C++ Program to implement Use of template
#include <iostream>
using namespace std;
template <class T, class U>
class A
{ T x;
U y;
public:
A()
{ cout << "Constructor Called" << endl; }
};
int main()
{ A<char, char> a;
A<int, double> b;
return 0;
}
Output
Constructor Called
Constructor Called
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
47. • Function-template specializations and class- template specializations
are like the separate tracings that all have the same shape, but could,
for example, be drawn in different colours.
• In other words, a template may be considered as a kind of macro.
• When the actual object of that type is to be defined, the template definition
is substituted with required data type.
• For example, if we define a template Array of elements, then this same
generic definition may be used to create Array of integers or of characters
or float quantities.
• We need not make a new class definition every time.
• We define a generic class with a parameter that s replaced by a particular
data type at the time of actual use of that class.
• This is the reason template classes are also known as parameterized
classes.
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
48. // C++ Program to implement
// template Array class
#include <iostream>
using namespace std;
template <typename T>
class Array
{
private:
T* ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
template <typename T> Array<T>::Array(T arr[], int s)
{
ptr = new T[s];
size = s;
for (int i = 0; i < size; i++)
ptr[i] = arr[i];
}
template <typename T>
void Array<T>::print()
{
for (int i = 0; i < size; i++)
cout << " " << *(ptr + i);
cout << endl;
}
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
Array<int> a(arr, 5);
a.print();
return 0;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
49. // C++ Program to implement
// template Array class
#include <iostream>
using namespace std;
template <typename T>
class Array
{
private:
T* ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
template <typename T> Array<T>::Array(T arr[], int s)
{
ptr = new T[s];
size = s;
for (int i = 0; i < size; i++)
ptr[i] = arr[i];
}
template <typename T>
void Array<T>::print()
{
for (int i = 0; i < size; i++)
cout << " " << *(ptr + i);
cout << endl;
}
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
Array<int> a(arr, 5);
a.print();
return 0;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
50. // C++ Program to implement
// template Array class
#include <iostream>
using namespace std;
template <typename T> class Array {
private:
T* ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
template <typename T> Array<T>::Array(T arr[], int s)
{
ptr = new T[s];
size = s;
for (int i = 0; i < size; i++)
ptr[i] = arr[i];
}
template <typename T> void Array<T>::print()
{
for (int i = 0; i < size; i++)
cout << " " << *(ptr + i);
cout << endl;
}
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
Array<int> a(arr, 5);
a.print();
return 0;
}
Output
1 2 3 4 5
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
51. //like normal parameters, we can specify default arguments to templates.
#include <iostream>
using namespace std;
template <class T, class U = char> class A {
public:
T x;
U y;
A() { cout << "Constructor Called" << endl; }
};
int main()
{
// This will call A<char, char>
A<char> a;
return 0;
}
Output
Constructor Called
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
52. What is the difference between function overloading and
Function templates?
Both function overloading and templates are examples of
polymorphism features of OOP.
Function overloading is used when multiple functions do
quite similar (not identical) operations,
But, Function templates are used when multiple functions
do identical operations.
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
53. Object Oriented Programming with C++
Course Code: CSE2001
UNIT 4 : Exception handling and Templates
UNIT 4 :Exception handling and Templates
4.1 Exception handling (user-defined exception)
4.2 Function template ,
4.3 Class template
4.4 Template with inheritance,
4.5 STL
4.6 Container,
4.7 Algorithm,
4.8 Iterator vector, list, stack, map
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
54. TEMPLATE WITH INHERITANCE
Template with inheritance in C++ allows you to create
generic classes and derive specialized classes from them, where
the derived classes inherit both the template parameters and
functionality from the base class.
This approach combines the benefits of templates and
inheritance, providing flexibility and code reusability.
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
55. Advantages of Template with Inheritance:
Code Reusability: Templates allow writing generic code
that can be reused with different data types, while
inheritance allows deriving specialized classes with
additional functionality.
Flexibility: Template with inheritance provides flexibility by
allowing derived classes to inherit both data types and
functionality from the base class template.
Abstraction: Templates and inheritance together allow you
to define abstract concepts and behaviors that can be
specialized and reused in different contexts.
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
56. TEMPLATE WITH INHERITANCE
Disadvantages of Template with Inheritance:
Complexity: Combining templates and inheritance can
increase the complexity of the code, especially in larger
projects, leading to potential confusion and maintenance
challenges.
Compilation Time: Templates can increase compilation
time, especially for complex code, as the compiler generates
code for each specific instantiation of the template.
Readability: Complex template code with inheritance
hierarchies can be difficult to read and understand, especially
for developers who are not familiar with advanced C++
features.
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
57. #include <iostream>
using namespace std;
// Template base class
template<typename T>
class Base {
protected:
T data;
public:
Base(T d) : data(d) {}
void display() {
cout << "Data: " << data << endl;
}
};
// Derived class from Base template
class Derived : public Base<int> {
private:
int value;
public:
Derived(int d, int v) : Base<int>(d), value(v) {}
void show() {
cout << "Derived Data: " << data << ", Value: " << value << endl;
}
};
int main() {
// Create objects of Base and Derived classes
Base<double> base(3.14);
base.display();
Derived derived(10, 20);
derived.display(); // Accessing base class function
derived.show(); // Accessing derived class function
return 0;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
58. #include <iostream>
using namespace std;
// Template base class
template<typename T>
class Base {
protected:
T data;
public:
Base(T d) : data(d) {}
void display() {
cout << "Data: " << data << endl;
}
};
// Derived class from Base template
class Derived : public Base<int> {
private:
int value;
public:
Derived(int d, int v) : Base<int>(d), value(v) {}
void show() {
cout << "Derived Data: " << data << ", Value: " << value << endl;
}
};
int main() {
// Create objects of Base and Derived classes
Base<double> base(3.14);
base.display();
Derived derived(10, 20);
derived.display(); // Accessing base class
function
derived.show(); // Accessing derived class
function
return 0;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
59. #include <iostream>
using namespace std;
// Template base class
template<typename T>
class Base
{
protected:
T data;
public:
Base(T d) : data(d) {}
void display()
{
cout << "Data: " << data << endl;
}
};
// Derived class from Base template
class Derived : public Base<int>
{
private:
int value;
public:
Derived(int d, int v) : Base<int>(d), value(v) {}
void show()
{
cout << "Derived Data: " << data << ", Value: " << value << endl;
}
};
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
60. int main()
{
// Create objects of Base and Derived classes
Base<double> base(3.14);
base.display();
Derived derived(10, 20);
derived.display(); // Accessing base class function
derived.show(); // Accessing derived class function
return 0;
}
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan
61. UNIT 4 _Part 2 Summary
In this Unit 4 _part2 we discussed the following topics,
UNIT 4 :Exception handling and Templates
4.1 Exception handling (user-defined
exception)
4.2 Function template ,
4.3 Class template
4.4 Template with inheritance ,
4.5 STL
4.6 Container,
4.7 Algorithm,
4.8 Iterator vector, list, stack, map
Unit 4_Part 1 CSE2001 Exception Handling and Function & Class Templates by Dr MK Jayanthi Kannan