The document discusses templates in C++. It begins by explaining function overloading and how templates provide a better approach than overloading by allowing identical operations to be performed on different data types with a single function. It then covers the different types of templates, including function templates and class templates. Examples are provided of bubble sort and linked lists implemented using templates. The key advantages of templates over macros are also summarized.
Introduction to the presentation on OOP using C++, presented by Dr. Chandra Sekhar Sanaboina from JNTU Kakinada.
Overview of major topics including Templates, Exception Handling, and Generic Programming.
Introduction to Generic Programming and advantages of using templates for code reusability.
Explanation of function and class templates as an approach to create reusable code for various data types.
Describes how to declare and implement function templates with examples showcasing swapping values.
Introduction to class templates that enable generic class implementations for various data types.
Example of a Calculator class template and concepts of function template overloading.
Implementation of a bubble sort function template to sort arrays of different data types.
Comparison between templates and macros in C++, highlighting key differences and advantages.
Introduction to exception handling, types of errors, and differences between compile-time and runtime errors.
Introduction to exception concepts in C++, keywords try, catch, and throw used in exception handling.
Discussion on synchronous and asynchronous exceptions and key principles of exception handling. Examples demonstrating how to implement and handle exceptions, including nested try-catch blocks.
Examples showing how to specify exceptions in functions and include custom exception handling.
Ending the presentation, summarizing the covered topics.
OOPS THROUGH C++
Dr.Chandra Sekhar Sanaboina
Assistant Professor
Department of Computer Science and Engineering
University College of Engineering Kakinada
Jawaharlal Nehru Technological University Kakinada
Website: https://drcs.info
1
Youtube Link:
https://www.youtube.com/watch?v=nPjHraTbPeY&list=PLT1ngltOnlJiHbzVvjkU8VzQt9oam8ji4
AGENDA
• Templates –
•Generic Programming with Templates
• Need for Templates
• Definition of class Templates
• Normal Function Templates
• Over Loading of Template Function
• Bubble Sort Using Function Templates
• Difference Between Templates and Macros
• Linked Lists with Templates
• Exception Handling
• Principles of Exception Handling
• The Keywords try throw and catch
• Multiple Catch Statements
• Specifying Exceptions
3
FUNCTION OVERLOADING –1
// overloading functions
#include <iostream>
using namespace std;
int operate (int a, int b)
{
return (a*b);
}
double operate (double a, double
b)
{
return (a/b);
}
int main ()
{
int x=5,y=2;
double n=5.0,m=2.0;
cout << operate (x,y) << 'n';
cout << operate (n,m) << 'n';
return 0;
}
Note: Both functions have quite
different behaviors, the int version
multiplies its arguments, while
the double version divides them.
This is generally not a good idea. Two
functions with the same name are
generally expected to have -at least-
a similar behavior
7
8.
FUNCTION OVERLOADING –2
// overloaded functions
#include <iostream>
using namespace std;
int sum (int a, int b)
{
return a+b;
}
double sum (double a, double b)
{
return a+b;
}
int main ()
{
cout << sum (10,20) << 'n';
cout << sum (1.0,1.5) << 'n';
return 0;
}
Note: sum is overloaded with different
parameter types, but with the exact same
body
Note: The function sum could be overloaded
for a lot of types, and it could make sense
for all of them to have the same body
8
9.
WHY TEMPLATES?
• Forcases such as this, C++ has the ability to define
functions with generic types, known as function templates
9
10.
EXAMPLE ON FUNCTIONOVERLOADING
#include <bits/stdc++.h>
using namespace std;
// Function to calculate square
void square(int a)
{
cout << "Square of " << a
<< " is " << a * a
<< endl;
}
// Function to calculate square
void square(double a)
{
cout << "Square of " << a
<< " is " << a * a
<< endl;
}
int main()
{
// Function Call for side as
// 9 i.e., integer
square(9);
// Function Call for side as
// 2.25 i.e., double
square(2.25);
return 0;
}
10
11.
GENERIC PROGRAMMING INTRODUCTION
•The method of Generic Programming is implemented to increase the efficiency of
the code
• Generic Programming enables the programmer to write a general algorithm which
will work with all data types
• It eliminates the need to create different algorithms if the data type is an integer,
string or a character
• Simply we can call it as Generics
11
12.
ADVANTAGES OF GENERICPROGRAMMING
• Code Reusability
• Avoid Function Overloading
• Once written it can be used for multiple times and
cases.
12
13.
ADVANTAGES OF GENERICPROGRAMMING
• Generics can be implemented in C++ using Templates
• Template is a simple and yet very powerful tool in C++
• The simple idea is to pass data type as a parameter so that we
don’t need to write the same code for different data types
• Example:
• A user need sort() for different data types
• Rather than writing and maintaining the multiple codes, we can write
one sort() and pass data type as a parameter
13
14.
PROGRAMMING EXAMPLE ONGENERICS
#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;
} 14
FUNCTION TEMPLATE
• Afunction template works in a similar to a normal function, with
one key difference
• A single function template can work with different data types at once
but, a single normal function can only work with one set of data types
• Normally, if you need to perform identical operations on two or
more types of data, you use function overloading to create two
functions with the required function declaration
• However, a better approach would be to use function templates
because you can perform the same task writing less and
maintainable code
18
19.
DECLARE FUNCTION TEMPLATE
•Function template starts with the keyword template followed by template parameters
inside <>
• It is followed by the function declaration
• Syntax:
template <class T>
T someFunction(T arg)
{
... .. ...
}
• In the above code, T is a template argument that accepts different data types (int, float), and class
is a keyword
• You can also use keyword typename instead of class in the above example
19
20.
FUNCTION TEMPLATE EXAMPLE
#include<iostream>
using namespace std;
template <typename T>
void Swap(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{
int i1 = 1, i2 = 2;
float f1 = 1.1, f2 = 2.2;
char c1 = 'a', c2 = 'b';
cout << "Before passing data to function template.n";
cout << "i1 = " << i1 << "ni2 = " << i2;
cout << "nf1 = " << f1 << "nf2 = " << f2;
cout << "nc1 = " << c1 << "nc2 = " << c2;
Swap(i1, i2);
Swap(f1, f2);
Swap(c1, c2);
cout << "nnAfter passing data to function template.n";
cout << "i1 = " << i1 << "ni2 = " << i2;
cout << "nf1 = " << f1 << "nf2 = " << f2;
cout << "nc1 = " << c1 << "nc2 = " << c2;
return 0;
} 20
CLASS TEMPLATE
• Likefunction templates, we can also create class templates for generic class
operations
• Sometimes, we need a class implementation that is same for all classes, only the
data types used are different
• Normally, we would need to create a different class for each data type OR create
different member variables and functions within a single class
• This will unnecessarily expand our code and will be hard to maintain, as a change
is one class/function should be performed on all classes/functions
• However, class templates make it easy to reuse the same code for all data types
22
23.
CLASS TEMPLATE DECLARATION
•Syntax:
template <class T>
class className
{
... .. ...
public:
T var;
T someOperation(T arg);
... .. ...
};
• T is the template argument which is a placeholder for the data type used
• Inside the class body, a member variable var and a member function someOperation() are both of
type T
23
24.
CREATE OBJECTS FORCLASS TEMPLATES
• Syntax:
• className<dataType> classObject;
• To create a class template object, we need to define the datatype inside a <> at its
creation
• Examples:
• className<int> classObject;
• className<float> classObject;
• className<string> classObject;
24
25.
CLASS TEMPLATE EXAMPLE
#include<iostream>
using namespace std;
template <class T>
class Calculator
{
private:
T num1, num2;
public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
void displayResult()
{
cout << "Numbers are: " << num1 << "
and " << num2 << "." << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() <<
endl;
cout << "Product is: " << multiply() <<
endl;
cout << "Division is: " << divide() << endl;
}
T add() { return num1 + num2; }
T subtract() { return num1 - num2; }
T multiply() { return num1 * num2; }
T divide() { return num1 / num2; }
};
int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
cout << "Int results:" << endl;
intCalc.displayResult();
cout << endl << "Float results:" << endl;
floatCalc.displayResult();
return 0;
}
25
OVERLOADING TEMPLATE FUNCTION
•The name of the function templates are the same but called with
different arguments is known as function template overloading
• A template function can be overloaded either by
• non-template function
• using an ordinary function template
• Using Non-Template Function:
• When a function template is overloaded with a non-template function, the
function name remains the same but the function’s arguments are unlike
• Using Ordinary Function Template:
• If the function template is with the ordinary template, the name of the
function remains the same but the number of parameters differs
27
28.
OVERLOADED TEMPLATE FUNCTION
(USINGEXTERNAL FUNCTION)
#include <bits/stdc++.h>
using namespace std;
// Template declaration
template <class T>
// Template overloading of function
void display(T t1)
{
cout << "Displaying Template: "
<< t1 << "n";
}
// Template overloading of function
void display(int t1)
{
cout << "Explicitly display: "
<< t1 << "n";
}
int main()
{
// Function Call with a
// different arguments
display(200);
display(12.40);
display('G');
return 0;
}
28
TEMPLATE VS MACRO
TemplateMacro
Only available in C++ Used in C and C++
Used to write small functions and classes Used for replacement of numbers, small
inline functions etc.,
More chances of making mistakes Code is simple and easier to understand
Easy to debug, because it undergoes
compilation process.
Difficult to handle errors as they are
handled by pre-processor
Being a function call, they are less efficient
than macros
More efficient as they are compiled
inline
They are considered to be type safe, as
there is compile time checking
Macros do not have any type checking
and therefore are type unsafe
33
34.
DATA TYPE CHECKING
MacroTemplate
#define swap(x, y)
int main ()
{
int i = 10;
float j = 12.2;
swap(i, j);
}
Note: swap() does not check the data
type
include <iostream>
template <typename T>
T swap(T &a, T &b)
{
T c;
c = b;
b = a;
a = c;
}
int main ()
{
int i = 10;
float j = 12.2;
swap(i, j);
}
34
35.
COMPILATION
Macro Template
Line:1:#define set_userid(x)
Line:2:current_user= x
Line:3:next_user = x + 1;
Line:4:int main (int argc, char *argv[]
)
Line:5:{
Line:6: int user = 10;
Line:7: set_userid(user);
Line:7:}
Error at Line 7
Note: Compiler is not giving the error
on line 2 where we have missing ";". It
is giving the error where the macro is
called (i.e., line 7)
#include <iostream>
template <typename T>
T swap(T &a, T &b)
{
T c;
c = b
b = a;
a = c;
}
int main ()
{
int i = 10;
int j = 12;
swap(i, j);
}
Note: Compiler is giving the error on
line 2 of template where we have
missing ";".
35
LINKED LIST WITHTEMPLATES
#include <iostream>
using namespace std;
template <typename T>
struct link //one element of list
{
T data; //data item
link* next; //pointer to next link
};
template <class T>
class linklist //a list of links
{
private:
link<T>* first; //pointer to first link
public:
linklist() //no-argument constructor
{ first = NULL; } //no first link
void additem(T d); //add data item (one link)
void display(); //display all links
};
template <class T>
void linklist<T>::additem(T d) //add data item
{
link<T> *newLink = new link<T>;
newLink->data = d;
//insert at head of link list
newLink->next = first;
first = newLink;
}
template <class T>
void linklist<T>::display() //display all links
{
link<T>* current = first; //set ptr to first link
while( current != NULL ) //quit on last link
{
cout << current->data << endl; //print data
current = current->next; //move to next link
}
}
int main()
{
linklist<int> li; //make linked list
li.additem(25); //add four items to list
li.additem(36);
li.additem(49);
li.display(); //display entire list
linklist<char> lch; //make linked list
lch.additem('a'); //add four items to list
lch.additem('b');
lch.additem('c');
lch.display(); //display entire list
return 0;
}
37
ERRORS AND TYPESOF ERRORS
• Error:
• An error is an interruption of code execution due to which
the expected output could not be obtained
• Types of Errors:
• Errors are Classified as
• Compile-Time Errors
• Run-Time Errors
• Note: Run-Time Errors are also called as bugs or
exceptions
40
41.
COMPILE TIME ERRORSVS RUN-TIME ERRORS
Compile-Time Errors Run-Time Errors
Occurs with respect to Syntax and Semantics Occurs during the execution of code at
runtime
Detected by compiler at the time of code
development
Not detected by the compiler but are
identified at the time of code execution
Fixed at the time of code development Fixed after code is executed and error gets
identified
Examples:
Missing ; , Missing braces, Missing
parentheses, Undefined Identifier
Examples:
Divide by Zero, Infinite Loop, Wrong Input by
the user, I/O errors, Undefined Object errors
We cannot run the code successfully till we
correct these errors
Stop the program from getting desired results
Example Code:
main(){
Int x=10;
cout<<x
}
Output: error at line 3:8: ; missing
Example Code:
main(){
int a=10;
int b=0;
cout<<a/b;
}
Output: Floating Point Exception
41
EXCEPTION INTRODUCTION
• Anexception is a problem that arises during the execution of a program
• Exceptions are run-time anomalies or abnormal conditions that a program
encounters during its execution
• 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
• Exceptions provide a way to transfer control from one part of a program to another
43
44.
EXCEPTION INTRODUCTION CONTD…
•C++ exception handling is built upon three keywords: try, catch, and throw
• try −
• A try block identifies a block of code for which particular exceptions will be activated
• It's followed by one or more catch blocks
• throw −
• Used to throw an exception
• Also used to list the exceptions that a function throws, but doesn’t handle itself
• This is done using a throw keyword
• catch −
• represents a block of code that is executed when a particular exception is thrown
• The catch keyword indicates the catching of an exception
44
45.
EXCEPTION INTRODUCTION CONTD…
•Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords
• A try/catch block is placed around the code that might generate an exception
• Code within a try/catch block is referred to as protected code
45
TYPES OF EXCEPTIONS
•There are two types of exceptions:
• Synchronous –
• Exception handling mechanism can handle only Synchronous Errors
• These exceptions are handled by try/catch
• They have a termination model – once the control is thrown from the try
block the control never returns back
• Asynchronous
• Cannot be handled by exception handling mechanisms in C++
• Hardware failures can be treated under this category
• Example:
• program’s control, Disc failure, keyboard interrupts etc.,
47
48.
WHY EXCEPTION HANDLING?
•Separation of Error Handling code from Normal Code
• Functions/Methods can handle any exceptions they choose
• Grouping of Error Types
48
49.
EXCEPTION HANDLING EXAMPLE
#include<iostream>
using namespace std;
int main()
{
int x = -1;
// Some code
cout << "Before try n";
try {
cout << "Inside try n";
if (x < 0)
{
throw x;
cout << "After throw (Never executed) n";
}
}
catch (int x ) {
cout << "Exception Caught n";
}
cout << "After catch (Will be executed) n";
return 0;
}
49
50.
IMPORTANT POINTS REGARDING
EXCEPTIONHANDLING
• There is a special catch block to catch all exceptions
• Implicit type conversion doesn’t happen for primitive types
• If an exception is thrown and not caught anywhere, the program terminates
abnormally
• A derived class exception should be caught before a base class exception
• C++ library has a standard exception class which is base class for all standard
exceptions
• In C++, all exceptions are unchecked…Compiler doesn’t check whether an
exception is caught or not
• Can use functions to specify all uncaught exceptions
• In C++, try-catch blocks can be nested
• When an exception is thrown, all objects created inside the enclosing try block are
destructed before the control is transferred to catch block
50
IF AN EXCEPTIONIS THROWN AND NOT
CAUGHT ANYWHERE, THE PROGRAM
TERMINATES ABNORMALLY
#include <iostream>
using namespace std;
int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught ";
}
return 0;
}
53
54.
A DERIVED CLASSEXCEPTION SHOULD BE
CAUGHT BEFORE A BASE CLASS EXCEPTION
#include<iostream>
using namespace std;
class Base {};
class Derived: public Base {};
int main()
{
Derived d;
// some other stuff
try {
// Some monitored code
throw d;
}
catch(Base b) {
cout<<"Caught Base Exception";
}
catch(Derived d) { //This catch block is NEVER executed
cout<<"Caught Derived Exception";
}
getchar();
return 0;
}
Note 1:
If both base and
derived classes are
caught as exceptions
then catch block of
derived class must
appear before the
base class
Note 2:
If we put base class
first then the derived
class catch block will
never be reached 54
55.
FUNCTION TO SPECIFYTHE UNCAUGHT
EXCEPTIONS
#include <iostream>
using namespace std;
void fun(int *ptr, int x)
{
if (ptr == NULL)
throw ptr;
if (x == 0)
throw x;
/* Some functionality */
}
int main()
{
try {
fun(NULL, 0);
}
catch(...) {
cout << "Caught exception from fun()";
}
return 0;
}
55
ALL OBJECTS CREATEDINSIDE THE ENCLOSING
TRY BLOCK ARE DESTRUCTED BEFORE THE
CONTROL IS TRANSFERRED TO CATCH BLOCK
include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "Constructor of Test " << endl; }
~Test() { cout << "Destructor of Test " << endl; }
};
int main()
{
try {
Test t1;
throw 10;
}
catch (int i) {
cout << "Caught " << i << endl;
}
}
57
PRINCIPLES OF EXCEPTIONHANDLING
• If you can't handle an exception, don't catch it
• Catch an exception as close as possible to its source
• If you catch an exception, don't swallow it
• Log an exception where you catch it, unless you plan to re-throw it
• Use as many typed exceptions as you need, particularly for application
exceptions
• By fine graining the throws clause, it is self-documenting and becomes evident to
the caller that different exceptions have to be handled.
• Never throw unchecked exceptions in your methods just because it clutters
the method signature
• Throw Application Exceptions as checked Exceptions and Unrecoverable
System exceptions as unchecked exceptions
• Structure your methods according to how fine-grained your exception
handling must be
59
CHECKED VS UNCHECKED
•Checked Exceptions –
• Checked Exceptions are those that extend java.lang.Exception.
• If your method throws checked exceptions, then the caller is
forced to catch these exceptions at compile time or declare in
the throws clause of the method
• Unchecked Exceptions –
• Unchecked exceptions are those that
extend java.lang.RuntimeException, generally referred to as
runtime exceptions
• If your method throws a runtime exception, the caller of the
method is not forced to catch the exception or add it to the
method signature at compile time
61
SPECIFYING EXCEPTIONS
• InC++, one can specify the exceptions through
functions
• The programmer can specify which type of exception
he/she wants to throw
63
64.
#include<iostream>
using namespace std;
voidtest(int x) throw (int,
double)
{
if(x==0)
throw 10;
else if(x==-1)
throw 15.34;
}
int main()
{
try{
test(0);
test(-1);
}
catch(int a)
{
cout<< "Integer caught "<<a;
}
catch(double d)
{
cout<< "double caught"<<d;
}
}
EXAMPLE - 1 ON SPECIFYING EXCEPTIONS
64