PDS 2 Unit 3 Notes
PDS 2 Unit 3 Notes
COM
ABSTRACT CLASS
The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class
from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves
only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error.
Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions,
which means that it supports the interface declared by the ABC. Failure to override a pure virtual
function in a derived class, then attempting to instantiate objects of that class, is a compilation error.
Classes that can be used to instantiate objects are called concrete classes.
EXCEPTION HANDLING
An exception is any unusual event, either erroneous or not, detectable by either hardware or software,
that may require special processing.
V+ TEAM
WWW.VIDYARTHIPLUS.COM
TRY BLOCK -The keyword try is used to preface a block of statements(surrounded by braces)
which may generate exceptions.
->When an exception is detected, it is thrown using a throw statement in the try block.
CATCH BLOCK - defined by the keyword catch catches the exception thrown by the throw
statement in the try block, and handles it appropriately.
EG:
#include <iostream>
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
int main()
cout << start;
try
{
// start a try block
cout << Inside try block\n;
throw 100;
// throw an error
cout << This will not execute;
}
catch (int i)
{
// catch an error
cout << caught an exception ;
cout << i ;
cout << End;
return 0;
}
}
Exception Types
Synchronous Exception:
Out of rage
Over flow
Asynchronous Exception
-Error that are caused beyond the control of the program
Keyboard interrupts
Division by zero
Access to an array outside of its bounds
Running out of memory
V+ TEAM
WWW.VIDYARTHIPLUS.COM
if(j==0)
{
cout<<RESULT IS <<i/j;
}
else
return 0;
}
#include<iostream.h>
int main()
{
int i,j;
cout << "Starts here\n";
i=10;
j=0;
try
{
// start a try block
cout << "Inside try block\n";
if(j==0)
{
throw j; // throw an error
cout << "This will not be printed \n";
}
cout<<RESULT IS <<i/j;
}
catch( int a)
{ // catch an error
cout << "The Number Caught is : ";
cout << a << "\n";
}
cout << "Ends here";
return 0;
}
When the program enters the try block it is said to be in the guarded section.
In this program when the value of j is zero an exception is created and thrown.
Note that the statements after throw statement in try block is not executed.
Once the exception is thrown the catch block catches the value (here zero) and handles it.
After that the program continues it normal execution.
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
-----}
#include<iostream.h>
void compute(int a,int b)
{
int c;
if(b==0)
{
throw b;
else
c=a/b;
}
cout<<RESULT OF THE DIVISION<<c;
}
void main()
{
int x,y;
cout<<ENTER TWO NUMBERS;
cin>>x>y;
try
{
compute(x/y); // fun generating exception
}catch(int k)
{
cout<<DIVIDE BY ZERO
EXCEPTION<<endl;
}
}
Throwing Mechanisms
An exception is thrown by using the throw keyword from inside the try block.
A throw expression accepts one parameter, which is passed as an argument to the exception
handler.
EX: throw b;
The throw statement will have the following EG: form
throw (exception)
throw exception
-- throw
Catching Mechanisms
if the data type specified by a catch, matches that of the exception, then catch statement is
executed.
When an exception is caught, arg will receive its value
syntax:
try
{
any statements
if (some condition) throw value1;
else if (some other condition) throw value2;
else if (some last condition) throw valueN;
}
catch (type1 name)
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
{
any statements
}
catch (type2 name)
{
any statements
}
catch (typeN name)
{
any statements
}
eg:
#include<iostream.h>
void multiple_catch(int value)
{
try
{
if (value==0) //throw an int value
throw 1;
else if (value==1) //throw a char
throw a;
else //throw float
throw 1.1;
}
catch(char c)
{
cout<<Character value is thrown <<c;
}
catch(int i)
{
cout<<Integer value is thrown<<i;
}
catch(float f)
{
cout<<Float value is thrown<<f;
}
}
void main()
{
cout<<Main Program<<endl;
multiple_catch(0);
multiple_catch(1);
multiple_catch(5);
}
Rethrowing Exceptions
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
syntax:
try
{
.
throw a;.
}
catch (char c)
{
throw;
}
eg:
#include <iostream.h>
class sam{
into erno;
public:
sam (int errno){
exno=errno;
}
void shoex()
{
cout<<error no:<<exno;
}
};
void ergen(){
try{
sam s1(20);
int c;
cin>>c;
switch (c)
{
case 1:
throw 10;
case 2:
throw a;
case 3:
throw s1;
case 4:
throw welcome;
}
catch (int ie)
{
cout<<ie<<ie;
throw; //rethrowing
}
catch (char ce)
{
cout <<ce<<ce;
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
throw; //rethrowing
}
}
void main (){
try{
ergen();
throw 10;
}
catch (int)
{
cout <<caught integer;
}
catch(char)
{
cout<<caught char;
}
catch (sam s2){
s2.show x();
}
}
Terminate Function
Use :
Terminate () is the function which calls abort() to exit the program in the event of run time error
related to exceptions
the user can provide his or her own terminate function instead of built-in terminate
Used to close all open files & deallocate resources before quitting the program.
Syntax: set_terminate (myterminate);
Unexpected Function
if a function throws an exception which is not allowed, a function unexpected () is called, which
in turn calls abort.
We can use set_unexpected in a similar to set_terminate
Syntax: set_unexcepted(my unexcepted);
eg:
#include <iostream>
void myunexpected ()
{
cout << "unexpected called\n";
throw 0; // throws int (in exception-specification)
}
void myfunction () throw (int)
{
throw 'x'; // throws char (not in exception-specification)
}
int main (void)
{
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
set_unexpected (myunexpected);
try {
myfunction();
}
catch (int)
{
cout << "caught int\n";
}
catch (...)
{
cout << "caught some other exception type\n";
}
return 0;
}
Uncaught Exception()
This function returns true if an exception has been thrown but not yet caught.
Once caught, the function returns false.
Syntax: bool uncaught_exceptions.
If (uncaught_exception())
{
//Do not call the function which might throw an exception
}
Otherwise
{
Follow the natural sequence of the destructor Algorithm
}
Generic programming
Generic programming means that you are not writing source code that is compiled as-is but that you write
"templates" of source codes that the compiler in the process of compilation transforms into source codes. The
simplest example for generic programming are container classes like arrays, lists or maps that contain a
collection of other objects. But there's much more to generic programming. In the context of C++ .it means to
write programs that are evaluated at compile time.
A basic example of generic programming are templates of containers: In a statically typed language like C++
you would have to declare separate containers that hold integers, floats, and other types or deal with pointers
to void and therefore losing all type information. Templates which are the C++ way of generic programming
leverage this constraint by letting you define classes where one or more parameters are unspecified at the time
you define the class. When you instance the template later you tell the compiler which type it should use to
create the class out of the template.
Example:
template<typename T>
class MyContainer
{
// Container that deals with an arbitrary type T
};
void main()
{
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
// Make MyContainer take just ints.
MyContainer<int> intContainer;
}
Templates
A significant benefit of object oriented programming is reusability of
code which eliminates redundant coding.
An important feature of oops called Templates makes this benefit
stronger and provides the greater flexibility to the languages
A template allows the construction of family of functions and classes to perform the same
operation on different types
This provides the generic programming which allows developing the
reusable software component such as classes and function
There are two types of templates
Function templates
Class templates
Terms which means use the same function or class for different purpose without changing their
basic meaning where the function or class should be defined only once
Templates are used to achieve reusability which eliminates redundant code
Class Templates
Class templates are used to create generic class witch support different data types.
Syntax:
template <class T>
class <class_name>
{
Member;
Member function;
};
Example:
#include<iostream.h>
#include<conio.h>
template <class T>
class complex
{
T real ,image;
public:
void getdata()
{
cout<<"\n Enter the complex values";
cin>>real>>image;
}
void putdata()
{
if(image>0)
cout<<real<<"+"<<image<<"i";
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
else
cout<<real<<image<"i";
}
};
void main()
{
clrscr();
complex <int> obj1;
obj1.getdata();
obj1.putdata();
complex <float> obj2;
obj2.getdata();
obj2.putdata();
getch();
}
Function Template
The template declared for function are function template
Function templates are generic function, which work for any data that is passed to them .
The data type is not specified while declaring the function
It performs appropriate operation depending on the data type we passed to them .
Syntax:
Template<typename T ,.>
Return Type Function-name(argument)
{
Function body
}
eg:
Template < class T>
Void generic Bubblesort(T Temp GenericArray[]) // template function 1
{
For( int i=0;i<5; i++)
{
For( int j=i+1;j<5;j++)
{
If(TempGenericArray[i]<TempGenericArray[j])
{
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
int temp=TempGenericArray[i];
TempGenericArray[i]=TempGenericArray[j];
TempGenericArray[j]=temp;
}
}
}
}
Template <class T>
Void Generic Display(T TempGenericArray[])
// template function2
{
Cout<<\n;
For(int i=0;i<5;i++)
{
Cout<<TempGenericArray[i]<<\t;
}}
Void main()
{
int Array1[]={1,4,6,2,6}
GenericBubbleSort(Array 1);
//calling function template 1
GenericDisplay(Array2);
// calling function template 2
Char Array2[]=sdfla;
GenaricBubbleSort(Array2)
//calling function template 1
Generic Display(Array 2);
Foat Array3[]={ 7.0,9.4,5.2,2.5,0.5);
GenericBubble Sort (Array 3); // calling function template 1
GenericBubbleSort( Array3 ); // calling function template 2
}
Sample output:
6
6
4
2
1
S
k
f
d
a
9.4
7
5.2
2.5
0.5
V+ TEAM
WWW.VIDYARTHIPLUS.COM
void main()
{
clrscr();
//void display(T1,T2);
display("sample","program");
display(10,20);
display(7.5,2);
display(10.75,10.256);
getch()
}
A stream is a sequence of bytes (or) conceptually pipe like constructs used for providing I/O.
Streams provide consistent interface for providing independence from having different
operations for different IO devices.
The source stream that provides data to the program is called the input stream.
The destination stream that receives output from the program is called the output stream.
Istream:
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
Ostream:
Streambuf:
Iostream:
cout<<variable 1<<.<<variable n;
this statement is used for displaying data on the screen.
EXAMPLE :
#include<iostream.h>
void main()
{
int a;
cout<<Enter a variable;
cin>>a;
cout<<The value of a is<<a;
}
getc() and putc() are used for reading and writing to the streams.
The getc() function has two different versions : 1. Void get(char)
WWW.VIDYARTHIPLUS.COM
2. char get(void)
V+ TEAM
WWW.VIDYARTHIPLUS.COM
Example :
#include<iostream.h>
#include<conio.h>
Void main ()
{
Int count=0;
Char c;
cout<<Enter a text;
cin.get(c);
while(c!=\n)
{
Cout.put(c);
Count++;
Cin.get(c);
}
Cout<<\n Number of characters = <<count;
}
the difference between getline() and read() is that : getline() terminates when a new line is
entered but read() does not stop when a new line is encountered.
read() stops only when end of file (ctrl + z ) is encountered .
The getline() also stops reading from input if end of file is specified.
Example:
#include<iostream.h>
#include<conio.h>
void main()
{
char msg[100];
Cin.getline(msg,100);
Cout.write(msg,5);
Cin.read(msg,10);
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
Cout.write(msg,5);
}
Output:
Object
Objec
getline()
Object
( ctrl + z )
objec
read()
4.setf() :
Example :
#include<iostream.h>
#include<conio.h>
Void main ()
{
Int n;
Cout.fill(*);
Cout.precision(3);
For(n=1;n<=b;n++)
{
Cout.width(5);
Cout<<n;
Cout.width(10);
Cout<<1.0/float(n)<<\n;
If(n>3)
Cout.fill(.);
}
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
Cout.fill(#);
Cout.width(15);
Cout<<12.345678;
}
MANIPULATORS :
Manipulators are special functions for formatting.
The choice between manipulators and ios functions to solve formatting problems sometimes depends
on the preference of the user.
Manipulators :
setw()
setprecison()
setfill()
setiosflags()
resetiosflags()
ios functions :
width()
precision()
fill()
setf()
unsetf()
program
#include<iostream.h>
#include<iomanip>
int main()
(
cout<<setw(15)<<setiosflags(ios::left)<<setiosflags(ios::fixed)<<setprecision(2)<<setiosflags(ios::showpoi
nt);
cout<<"Roll Number"<<setw(15)<<"Name"<<setw(10)<<setprecision(2)<<"Marks"<<endl;
cout<<setw(15)<<1<<setw(15)<<"Lara"<<setw(10)<<setprecision(2)<<355.50<<endl;
cout<<setw(15)<<2<<setw(15)<<"Beckham"<<setw(10)<<setprecision(2)<<275.00<<endl;
cout<<setw(15)<<3<<setw(15)<<"Steffi"<<setw(10)<<setprecision(2)<<290.75<<endl;
cout<<setw(15)<<4<<setw(15)<<"Jaspal"<<setw(10)<<setprecision(2)<<295.00<<endl;
cout<<setw(15)<<5<<setw(15)<<"Parker"<<setw(10)<<setprecision(2)<<200.60<<endl;
}
Characteristics of manipulators:
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
When a manipulator does not take any arguments , it is passed without the () parenthesis.
Some manipulators are needed in pairs to produce the toggle effect.
They are non-member-functions.
FILE HANDLING
INTRODUCTION:
OS is the primary interface between the user and the computer. Device driver is a small program that
comes with every device IO operations are performed with the help of the OS and the device driver.
A C++ program does not directly request to the OS. It invokes a function from a standard library that
comes with a C++ compiler , when it is installed.
Binary streams:
-binary values are inserted
- no conversion takes place.
The binary stream files are restricted to the application that creates the file. Binary files are not flexible.
Dealing With Text Files
Defining Files
ifstream < filename> - read only file
ofstream <filename> - output /write only file
fstream <file name > - both input/read and output /write file.
Manipulating Files
Opening Files :
-files can be opened using two methods
(i) using constructors
(ii) using open functions
Ifstream DisplayFile ( Fewlines.dat); (using constructors)
-it is an ios::in (input mode).
-for output mode replace ifstream by ofstream.
-in the above example fewlines is a physical file name. Displayfile is a logical file name.
-the logical files will vanish when the program is over, but physical files will be available in the
OS.
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
Displayfile.open(fewlines.dat);
V+ TEAM
WWW.VIDYARTHIPLUS.COM
}
entryfile.close();
ifstream displayfile("fewlines.dat");
while(!displayfile.eof())
{
displayfile.unsetf(ios::skipws);
displayfile>>ch;
cout<<ch;
}
displayfile.close();
return 0;
}
V+ TEAM
WWW.VIDYARTHIPLUS.COM
file_name.close();
or
file_object.close();
-it deallocates the files and flushes the buffer.
Using Binary Files :
-fail() and eof() are used.
Program pg 567
RANDOM ACCESS :
In C++ , there are two types of file pointers to access a file in a random manner.
For a file in the read mode seekg (pointer for reading or getting)
For a file in the write mode seekp(pointer for wrioting or putting)
Using these , it is possible to search any record of any file by skipping the other records inbetween.
seekg() and seekp() :
seekg() to move get or read pointer of file.
It takes two arguments , (i) number of bytes to skip (ii) from where to skip
seekp() to move put and write pointers.
tellg() and tellp() :
these pointers tell us where the read and write pointers of a file are pointing to.
tellg() tells us where the get pointer is pointing to.
tellp() tells us where the put pointer is pointing to.
Example:
#include"stdafx.h"
#include<iostream>
#include<fstream>
struct record
{
char code[6];
char name[20];
int i;
}r;
int main()
{
std::fstream file("Temp.dat",std::ios::trunc|std::ios::in|std::ios::out|std::ios::binary);
if(!file)
{
std::cout<<"unable to open file";
exit(0);
}
std::cout<<"enter character code, name and an int\n";
std::cin.getline(r.code,6);
std::cin.getline(r.name,20);
WWW.VIDYARTHIPLUS.COM
V+ TEAM
WWW.VIDYARTHIPLUS.COM
std::cin>>r.i;
file.write((char *)&r,sizeof(r));
std::cout<<"\n\n"<<file.tellg()<<'\n'<<file.tellp();
file.seekg(3);
std::cout<<"\n\n"<<file.tellg()<<'\n'<<file.tellp();
file.seekp(5);
std::cout<<"\n\n"<<file.tellg()<<'\n'<<file.tellp();
}
WWW.VIDYARTHIPLUS.COM
V+ TEAM