0% found this document useful (0 votes)
20 views45 pages

Unit V - OOP

The document covers Unit V of a C++ programming course, focusing on templates, namespaces, and exception handling, along with C++ streams. It details the concepts of function and class templates, the rules of namespaces, and the mechanisms for throwing and catching exceptions. Additionally, it provides references to textbooks and online resources for further learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views45 pages

Unit V - OOP

The document covers Unit V of a C++ programming course, focusing on templates, namespaces, and exception handling, along with C++ streams. It details the concepts of function and class templates, the rules of namespaces, and the mechanisms for throwing and catching exceptions. Additionally, it provides references to textbooks and online resources for further learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 45

Unit V Templates, Namespaces and Exception

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.

January 20, 2021 1


Object Oriented Programming: CO-PO
Mapping
Course Blooms After successful completion of the Mapping with
PO MAPPING
Outcome Taxonomy Level course students will be able to Syllabus Unit
Apply Templates, Namespaces and
Exception Handling concepts to write
CO204194.5 4 5
programs in C++.
MAPPING LEVEL JUSTIFICATION
Program Outcomes (POs)
1.Unit V (06knowledge
Engineering Hrs)
2. Problem analysis
3.•Templates
Design/development of solutions
4.•Namespaces
Conduct investigations of complex problems
5.• Modern tool usage
Exception handling
6. The engineer and society
•Stream Classes
7. Environment and sustainability
8. Ethics
9. Individual and team work
10. Communication
11. Project management and finance
12. Life-long learning
January 20, 2021 2
Books
TEXT BOOKS
1. E Balagurusamy, “Programming with C++”, Tata McGraw Hill, 3 rd Edition.
2. Herbert Schildt, “The Complete Reference C++”, 4 th Edition.

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/

January 20, 2021 3


OOP: Topic – Book – Pages Mapping
Reference / text book with
Sr. No. Topic
page no.

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/

4 Stream Classes E Balagurusamy, “Programming with C++”, Tata


McGraw Hill, 3rd Edition.
https://www.geeksforgeeks.org/

January 20, 2021 4


OOP: Unit V
Contents
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.

January 20, 2021 5


Polymorphism
Polymorphism
◦ “ability to assume different forms”
◦ one object acts like many different types of objects (e.g., Shape*)
◦ getting the right behavior without knowing the type
◦ manipulate objects with a common set of operations

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.

template <class T>


T maximum(T a, T b, T c)

int i1, i2, i3;

int m = maximum(i1, i2, i3);

maximum(i1, i2, i3) will invoke the template function with T==int. The function returns a value of int type.

10
Function Templates Usage

Each call to maximum() on a different data type forces the


compiler to generate a different function using the template.

◦ One copy of code for many types.

int i1, i2, i3;


cout << "The maximum integer value is:” << maximum( i1, i2, i3 );

double d1, d2, d3;


cout << "The maximum double value is:” << maximum( d1, d2, d3 );

11
Another example

template< class T >


void printArray( const T *array, const int count )
{
for ( int i = 0; i < count; i++ )
cout << array[ i ] << " "; cout << endl;
}

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(); }
}
};

January 20, 2021 16


Can there be more than one arguments to templates? –Yes

#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.

January 20, 2021 18


What is the difference between function overloading and templates?

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.

January 20, 2021 19


Questions:
How templates work?
What happens when there is static member in a template class/function?
What is template specialization?
Can we pass nontype parameters to templates?
Can we specify default value for template arguments?
Can there be more than one arguments to templates?

January 20, 2021 20


Namespaces
Namespaces allow us to group named entities that otherwise would have global scope into
narrower scopes, giving them namespace scope. This allows organizing the elements of
programs into different logical scopes referred to by names.
• Namespace is a feature added in C++ and not present in C.
• A namespace is a declarative region that provides a scope to the identifiers (names of the
types, function, variables etc) inside it.
• Multiple namespace blocks with the same name are allowed. All declarations within those
blocks are declared in the named scope.
• Namespace declarations appear only at global scope.
• Namespace declarations can be nested within another namespace.
• Namespace declarations don’t have access specifiers. (Public or private)
• No need to give semicolon after the closing brace of definition of namespace.
• We can split the definition of namespace over several units.

January 20, 2021 22


#include <iostream>
using namespace std;
namespace first
{
int val = 500;
}
int val = 100;
int main()
{ int val = 200;
cout << first::val << '\n';
return 0;
}

January 20, 2021 23


#include <iostream> int main()
using namespace std; {
namespace ns1
cout << ns1::value() << '\n';
{
int value() { return 5; }
} cout << ns2::value() << '\n';

namespace ns2
{ cout << ns2::x << '\n';
const double x = 100;
return 0;
double value() { return 2*x; } }
}

January 20, 2021 24


“using namespace std”
▪ It means we use the namespace named std.
▪ “std” is an abbreviation for standard.
▪ So that means we use all the things with in “std” namespace.
▪ If we don’t want to use this line of code, we can use the things in this namespace like this.
std::cout, std::endl.

January 20, 2021 25


▪ Can create classes in a namespace.
▪ Can Extend namespace.
▪ Can define methods outside namespace.
▪ Nesting, aliasing is also possible.

January 20, 2021 26


Exception Handling
• Exception is an unexpected problem arises during execution of program.

• 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.

January 20, 2021 27


Exception Handling
One of the advantages of C++ over C is Exception Handling.
Why Exception Handling?
1) Separation of Error Handling code from Normal Code
2) Functions/Methods can handle any exceptions they choose
3) Grouping of Error Types

There are two types of exceptions


a)Synchronous, b)Asynchronous

January 20, 2021 28


C++ provides following specialized keywords for this purpose.

try: represents a block of code that can throw an exception.

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.

January 20, 2021 29


#include <iostream>
int main ()
using namespace std; {
double division(int a, int b) int x = 50; int y = 0; double z = 0;
try {
{ z = division(x, y);
if( b == 0 ) cout << z << endl;
}
{ catch (const char* msg)
throw "Division by zero condition!"; {
cerr << msg << endl;
} }
return (a/b); return 0;
}
}

January 20, 2021 30


int main() catch (int x ) {
{ cout << "Exception Caught \n";
int x = -1; }
cout << "Before try \n";
cout << "After catch (Will be executed) \n";
try { return 0;
cout << "Inside try \n"; }
if (x < 0)
{
throw x;
cout << "After throw (Never executed) \n";
}
}
January 20, 2021 31
Multiple catch
#include<iostream.h> catch (char x)
#include<conio.h> {
void test(int x) cout << "Catch a character and that character is:" << x;
}}
{ void main()
try { {
if (x > 0) clrscr();
cout << "Testing multiple catches\n:";
throw x;
test(10);
else throw 'x'; test(0);
} getch();
}
catch (int x)
{ cout << "Catch a integer and that integer
is:" << x;
}

January 20, 2021 32


There is a special catch block called ‘catch all’ catch(…) that can be used to catch all types of
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. All
objects thrown by components of the standard library are derived from this class.

January 20, 2021 33


#include <iostream>
using namespace std;
int main()
{
try {
throw 'a'; }
catch (int x) {
cout << "Caught " << x;
}
catch (...) {
cout << "Default Exception\n";
}
return 0; }
January 20, 2021 34
#include<iostream> catch(Base b) {
using namespace std; cout<<"Caught Base Exception";
}
class Base {}; catch(Derived d) {
class Derived: public Base {}; cout<<"Caught Derived Exception";
int main() }
{
getchar();
Derived d; return 0;
// some other stuff }
try {
// Some monitored code
throw d; Output: Caught Base Exception
}

January 20, 2021 35


#include<iostream> catch(Derived d) {
using namespace std; cout<<"Caught Derived Exception";
}
class Base {}; catch(Base b) {
class Derived: public Base {}; cout<<"Caught Base Exception";
int main() }
{
Derived d; getchar();
// some other stuff return 0;
try { }
// Some monitored code
throw d;
} Output: Caught Derived Exception

January 20, 2021 36


Stream
• Stream is general name given to flow of data

• 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

January 20, 2021 37


Stream Classes
In C++ there are number of stream classes for defining various streams related with files and for
doing input-output operations. All these classes are defined in the file iostream.h.

January 20, 2021 38


1. ios class is topmost class in the stream classes hierarchy. It is the base class for istream,
ostream, and streambuf class.

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

January 20, 2021 39


Input/Output Streams
The iostream standard library provides cin and cout object.
Input stream uses cin object for reading the data from standard input and Output stream
uses cout object for displaying the data on the screen or writing to standard output.
The cin and cout are pre-defined streams for input and output data.
Syntax:
cin>>variable_name;
cout<<variable_name;
The cin object uses extraction operator (>>) before a variable name while the cout object
uses insertion operator (<<) before a variable name.

January 20, 2021 40


Unformatted I/O
The printed data with default setting by the I/O function of the language is known
as unformatted data.
It is the basic form of input/output and transfers the internal binary representation of the data
directly between memory and the file.
For example, in cin statement it asks for a number while executing. If the user enters a decimal
number, the entered number is displayed using cout statement. There is no need to apply any
external setting, by default the I/O function represents the number in decimal format.

January 20, 2021 41


Formatted I/O
C++ helps you to format the I/O operations like determining the number of digits to be displayed after the
decimal point
Example:
1. If we want to add + sign as the prefix of out output, we can use the formatting to do so:
stream.setf(ios::showpos)
If input=100, output will be +100
2. If we want to add trailing zeros in out output to be shown when needed using the formatting:
stream.setf(ios::showpoint)
If input=100.0, output will be 100.000

..stream is referred to the streams defined in c++ like cin, cout, cerr, clog.

January 20, 2021 42


There are two ways to do so:
1. Using the ios class or various ios member functions.
2. Using manipulators(special functions)

January 20, 2021 43


Formatting using Manipulators
The standard manipulators are shown below:
boolalpha: The boolalpha manipulator of stream manipulators in C++ is used to turn on bool alpha flag
dec: The dec manipulator of stream manipulators in C++ is used to turn on the dec flag
endl: The endl manipulator of stream manipulators in C++ is used to Output a newline character.
and: The and manipulator of stream manipulators in C++ is used to Flush the stream
ends: The ends manipulator of stream manipulators in C++ is used to Output a null
fixed: The fixed manipulator of stream manipulators in C++ is used to Turns on the fixed flag
flush: The flush manipulator of stream manipulators in C++ is used to Flush a stream
hex: The hex manipulator of stream manipulators in C++ is used to Turns on hex flag
internal: The internal manipulator of stream manipulators in C++ is used to Turns on internal flag
left: The left manipulator of stream manipulators in C++ is used to Turns on the left flag

January 20, 2021 44


cout << setiosflags(ios::showpos);
cout << 123<<"\n"; Output:
+123
// hexadecimal base (i.e., radix 16) 64
*****+2343
cout << hex << 100 << endl;

// Set the field width


cout << setfill('*') << setw(10) << 2343.0;

January 20, 2021 45

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy