Unit V - OOP
Unit V - OOP
handling
(06 Hrs)
• Templates: Introduction, Function template and class template,
function overloading vs. function templates
• Namespaces: Introduction, Rules of namespaces
• Exception handling: Introduction, basics of exception handling,
exception handling mechanism, throwing and catching mechanism,
specifying exceptions, Multiple Exceptions, Exceptions with
arguments
• C++ streams, stream classes, unformatted I/O, formatted I/O and
I/O manipulators.
REFERENCE BOOKS
1. Robert Lafore, “Object Oriented Programming in C++”, Sams Publishing, 4 th Edition.
2. Matt Weisfeld, “The Object-Oriented Thought Process”, Pearson Education.
ADDITIONAL MATERIAL
MOOC / NPTEL Courses:
1. NPTEL Course “Programming in Java” https://nptel.ac.in/courses/106/105/106105191/
2. NPTEL Course “Programming in C++” https://nptel.ac.in/courses/106/105/106105151/
3. https://www.geeksforgeeks.org/
UNIT V
1 Templates E Balagurusamy, “Programming with C++”, Tata
McGraw Hill, 3rd Edition.
2 Namespaces E Balagurusamy, “Programming with C++”, Tata
McGraw Hill, 3rd Edition.
https://www.geeksforgeeks.org/
3 Exception handling
E Balagurusamy, “Programming with C++”, Tata
McGraw Hill, 3rd Edition.
https://www.geeksforgeeks.org/
Two types:
◦ Run-time (Virtual functions)
◦ Compile-time (Templates)
Templates
Type-independent patterns that can work with multiple data types.
◦ Generic programming
◦ Code reusable
Function Templates
◦ These define logic behind the algorithms that work for multiple data types.
Class Templates
◦ These define generic class patterns into which specific data types can be plugged in to produce new
classes.
7
Function template
C++ routines work on specific types. We often need to write different routines to
perform the same operation on different data types.
int maximum(int a, int b, int c) float maximum(float a, float b, float c) double maximum(double a, double b, double c)
{
{ {
double max = a;
int max = a; float max = a;
if (b > max) max = b;
if (b > max) max = b; if (b > max) max = b;
if (c > max) max = c;
if (c > max) max = c; if (c > max) max = c;
return max;
return max; return max; }
} }
The logic is exactly the same, but the data type is different.
•Function templates allow the logic to be written once and used for all data types – generic function.
8
Function Templates
Generic function to find a maximum value
template <class T>
T maximum(T a, T b, T c)
{
T max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
}
Template function itself is incomplete because the compiler will need to know the actual type to generate
code. So template program are often placed in .h or .hpp files to be included in program that uses the
function.
C++ compiler will then generate the real function based on the use of the function template.
9
Function Templates Usage
After a function template is defined, the function can be used by passing
parameters of real types.
maximum(i1, i2, i3) will invoke the template function with T==int. The function returns a value of int type.
10
Function Templates Usage
11
Another example
12
#include <iostream>
using namespace std;
int main()
{
template <typename T> cout << myMax<int>(3, 7) << endl;
T myMax(T x, T y) cout << myMax<double>(3.0, 7.0) <<
{ endl;
return (x > y)? x: y; cout << myMax<char>('g', 'e') << endl;
} return 0;
}
13
Usage
template< class T >
void printArray( const T *array, const int count );
char cc[100];
int ii[100];
double dd[100];
……
printArray(cc, 100);
printArray(ii, 100);
printArray(dd, 100);
14
Class template
o Class Templates are useful when a class defines something that is independent
of the data type.
o Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc.
o Function templates allow writing generic functions that work on many types.
o Same idea applies to defining generic classes that work with many types --
extract the type to be a template to make a generic classes.
15
template <typename T>
template <typename T> template <typename T>
class Array { int main() {
Array<T>::Array(T arr[], int s) { void Array<T>::print() {
private:
int arr[5] = {1, 2, 3, 4, 5};
ptr = new T[s]; for (int i = 0; i < size; i++)
T *ptr;
Array<int> a(arr, 5);
int size; size = s; cout<<" "<<*(ptr + i);
public: a.print();
for(int i = 0; i < size; i++) cout<<endl;
Array(T ptr[], int s); return 0;
ptr[i] = arr[i]; }
void print(); }
}
};
#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;
}
January 20, 2021 17
Features
oTemplates are expanded at compiler time. This is like macros.
oThe difference is, compiler does type checking before template expansion.
oThe idea is simple, source code contains only function/class, but compiled code may contain
multiple copies of same function/class.
Both function overloading and templates are examples of polymorphism feature of OOP.
Function overloading is used when multiple functions do similar operations, templates are used
when multiple functions do identical operations.
namespace ns2
{ cout << ns2::x << '\n';
const double x = 100;
return 0;
double value() { return 2*x; } }
}
• Exceptions are run-time anomalies or abnormal conditions that a program encounters during its
execution.
• Exception handling mechanism provide way to transfer control from one part of program to
another.
catch: represents a block of code that is executed when a particular exception is thrown.
throw: Used to throw an exception. Also used to list the exceptions that a function throws, but
doesn’t handle itself.
• In C++, a stream refers to a sequence of characters that are transferred between the program
and input/output (I/O) devices. Stream classes in C++ facilitate input and output operations on
files and other I/O devices. These classes have specific features to handle program input and
output, making it easier to write portable code that can be used across multiple platforms.
• Stream is sequence of bytes
• Source stream that provide data to program is called input stream
• Header <iostream>, a set of class supports I/O operations
2. istream and ostream serves the base classes for iostream class. The class istream is used for
input and ostream for the output.
3. Class ios is indirectly inherited to iostream class using istream and ostream. To avoid the
duplicity of data and member functions of ios class, it is declared as virtual base class when
inheriting in istream and ostream
..stream is referred to the streams defined in c++ like cin, cout, cerr, clog.