Sie sind auf Seite 1von 26

File Input and Output Stream

File I/O

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

Opening Files
For opening a file, we must first create a file stream and then link it to the filename. A file stream can be defined using the classes ifstream, ofstream, and fstream that are contained in the header file fstream. The class to be used depends on read or write. A file can be open in two ways: Using the constructor function of the class.
Useful when we use only one file in the stream.

Opening Files Using Constructor


This involves two steps: Create a file stream object to manage the stream using appropriate class.
The class ofstream used to create output stream. The class ifstream to create input stream.

Initialize the file object with the desired filename.


Dr K.Srinivas Object Oriented Programming Systems

Using the member function open( ) of the class.


Use to manage multiple files using one stream. Dr K.Srinivas
May 3, 2011 Object Oriented Programming Systems 3 May 3, 2011 4

Opening Files Using Constructor


continue

Opening Files Using Open( )


The open( ) can be used to open multiple files that use the same stream object.

ofstream outfile (results); ifstream infile(data);


Output Stream
outfile

Disk

Result File

For processing a set files sequentially.

Program

file-stream-class stream-object;
Input Stream
infile
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 5 May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 6

Data File

stream-object.open ( file_name );

Opening Files Using Open( )


continue ofstream outfile; outfile.open(DATA1); .. outfile.close( ); outfile.open(DATA2); outfile.close( ); ......... The above program segment opens two files in sequence for writing the data. The first file is closed before opening the second one. A stream can be connected to only one file at a time.
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 7 May 3, 2011

File Modes
stream-object.open(file_name, mode); The second argument mode specifies the purpose for which the file is opened. Default values for these second parameters:
ios::in for ifstream - reading only ios::out for ofstream - writing only

Dr K.Srinivas Object Oriented Programming Systems

File Modes
continue ios::app ios::ate ios::binary ios::in ios::nocreate ios::noreplace ios::out ios::trunc
Append to end-of-file

Detecting End-Of-File
while (fin)
An ifstream object fin returns a value 0 if any error occurs in the file operation including the end-of-file condition. So the while loop may terminates when fin returns a value of zero on reaching the end-of-file condition.

Go to end-of-file on opening Binary file Open file for reading only Open fails if the file does not exist Open files if the file already exists Open file for writing only
Delete the contents of the file if it exists

if(fin1.eof() != 0) {exit(1);}
eof( ) is a member of ios class. It returns a non-zero value if the end-of-file (EOF) condition is encountered, and a zero, otherwise.
9 May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 10

fout.open(data, ios::app | ios :: nocreate)

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

Writing Text file

Reading Text file

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

11

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

12

Unformatted and Binary I/O


get() and put() functions
Read and write unformatted data is by using the member functions get() and put(). Syntax is: istream &get(char &ch); ostream &put(char ch); get()- reads a single character from the associated stream and puts that value in ch. Put()- writes ch to the stream and returns a reference to the stream.
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 13 May 3, 2011

Program displays the content of any file on the screen


#include <iostream> #include <fstream> using namespace std; int main(int argc, char *argv[]) { char ch; if(argc!=2) { cout << "Usage: PR <filename>\n"; return 1; } ifstream in(argv[1], ios::in | ios::binary); if(!in) { cout << "Cannot open file."; return 1; } while(in) { // in will be false when eof in.get(ch); if(in) cout << ch; } return 0; }
is reached

Dr K.Srinivas Object Oriented Programming Systems

14

Write the String to File


#include <iostream> #include <fstream> using namespace std; int main(int argc, char *argv[]) { char *p= Hell how r u\n; ofstream out(test, ios::out | ios::binary); if(!out) { cout << "Cannot open file."; return 1; } while(*p) out.put(*p++); out.close(); return 0; }
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 15

Sequential Input and Output Operations


continue

write( ) and read( ) Functions The functions write( ) and read ( ) handle the data in binary form. The values are stored in the disk file in the same format in which they are stored in the internal memory. An int takes two bytes to store its value in the binary form, irrespective of its size. But a 4 digit int will take four bytes to store it in the character form.
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 16

Sequential Input and Output Operations


continue

Sequential Input and Output Operations


continue

Representing 2594
I 2 Bytes I Binary Format I 9 4 Character Format

infile.read((char *) &V, sizeof(V)); outfile.write((char *) &V, sizeof(V)); write( ) and read( ) functions take two arguments.
First is the address of the variable V Second is the length of that variable in bytes. The address of the variable must be cast to type char * (pointer to character type).
Dr K.Srinivas Object Oriented Programming Systems

00001010 00100010

I 2 5

4 Bytes

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

17

May 3, 2011

18

Reading and Writing a Class Object


The read( ) and write( ) are also used to read from or write to the disk files objects directly. The read( ) and write( ) handle the entire structure of an object as a single unit, using the computers internal representation of data. Only data members are written to the disk files.

Program: read() & Write()


#include <iostream> #include <fstream> using namespace std; int main() { double fnum[4] = {99.75, 34.4, 1776.0, 200.1 }; int i; ofstream out("numbers", ios::out | ios::binary); if(!out) { cout << "Cannot open file."; return 1; } out.write((char *) &fnum, sizeof fnum); out.close();

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

19

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

20

Program: read() & Write()


for(i=0; i<4; i++) // clear array fnum[i] = 0.0; ifstream in("numbers", ios::in | ios::binary); in.read((char *) &fnum, sizeof fnum); // see how many bytes have been read cout << in.gcount() << " bytes read\n"; for(i=0; i<4; i++) // show values read from file cout << fnum[i] << " "; in.close(); return 0; }

Updating A File : Random Access


The size of each object can be obtained using the statement int object_length = sizeof(object); The location of a desired object, say mth object int location = m * object_length; The location gives the byte number of the first byte of the mth object. Now we can use seekg( ) or seekp( ) to set the file pointer to reach this byte.

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

21

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

22

File Pointer
Input Pointer (get pointer)
The input pointer is used for reading contents of a given file location.

File Pointer Default Actions


When a file opened in read-only mode, the input pointer is automatically set at the beginning of the file. When a file is opened in write-only mode, the existing contents are deleted and the output pointer is set at the beginning. When a file is opened in append mode, the output pointer moves to the end of file.
23 May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 24

Output Pointer (put pointer)


The output pointer is used for writing to a given file location.

Each time an input or output operation takes place, the appropriate pointer is automatically advanced.
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems

Functions for Manipulations of File Pointers


seekg( ) Moves get pointer (input) to a specified location. Moves put pointer(output) to a specified location. Gives the current position of the get pointer. Gives the current position of the put pointer.
Dr K.Srinivas Object Oriented Programming Systems 25

Seek Function with Absolute Position


infile.seekg(10); Moves the file pointer to the byte number 10 The bytes in a file are numbered beginning from zero.

seekp( )

tellg( )

tellp( )
May 3, 2011

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

26

Seek Function with Specifying the Offset


seekg( offset, refposition); seekp( offset, refposition);
The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by the parameter refposition. The refposition takes one of the following three constants defined in the ios class:
ios : : beg ios : : cur ios : : end
May 3, 2011

Seek Function with Specifying the Offset


fout.seekg(0, ios : : beg); fout.seekg(0, ios : : cur); fout.seekg(0, ios : : end); fout.seekg(m, ios : : beg); fout.seekg(m, ios : : cur); fout.seekg(fout.seekg(-m, ios : : cur); fout.seekg(fout.seekg(-m, ios : : end)
Go to start Stay at the current position Go to the end of file Move to (m+1)th byte in the file Go forward by m bytes from the current position Go backward by m bytes from the current position Go backward by m bytes from the end

start of the file current position of the pointer end of the file
Dr K.Srinivas Object Oriented Programming Systems 27

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

28

Reading and Writing a Class Object


int main() { Student stu[3]; fstream file; file.open(student.dat,ios::in|ios::out); cout<<Enter Student Details\n; for(int I=0; I<3;I++) { stu[I].readdata(); file.write((char *) & stu[I],sizeof(stu[I])); } file.seekg(0); cout<<\n Student details are:\n; for(int I=0; I<3;I++) { file.read((char *) & stu[I],sizeof(stu[I])); stu[I].writedata(); } file.close(); return 0; }
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 29

Templates
The C++s most advanced features: Templates, exceptions, runtime type ID (RTTI), and the casting operators Using templates, it is possible to create generic functions and classes. Generic Functions A generic function defines a general set of operations that will be applied to various types of data Ex: Quick sort algorithm is the same weather it is to an array of intergers or an array of floats. A generic function is created with the keyword template.
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 30

General form of a Template Function


A function is generated from a function template is called a function template. The general form of a template function definition is as follows Template <class T> returntype functionname (parameter list of type T) { // body of function }
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 31 May 3, 2011

#include <iostream> using namespace std; template <class T> void swap(T &x, T &y) { T temp =x; x= y; y=temp; } void function(int m,int n, float a, float b) { cout<<m and n values before swap:<<m<<n<<\n; swap(m,n); cout<<m and n values after swap:<<m<<n<<\n; cout<<a and b values before swap:<<a<<b<<\n; swap(a,b); cout<<m and n values before swap:<<a<<b<<\n; } int main() { function(100,200,100.23,200.54); return 0; }
Dr K.Srinivas Object Oriented Programming Systems 32

Bubble Sort using Template Function


#include <iostream> using namespace std; template <class T> void bubble_sort(T a[], int size); template <class T> void show_items(T a[], int size); int main(void) { int x[7] = {7, 5, 4, 3, 9, 8, 6}; double y[5] = {4.2, 2.5, -0.9, 1.2, 3.0}; cout << "Here is unsorted integer array: " << endl; show_items(x, 7); cout << "Here is unsorted double array: " << endl; show_items(y, 5); bubble_sort(x, 7); bubble_sort(y, 5); cout << "Here is sorted integer array: " << endl; show_items(x, 7); cout << "Here is sorted double array: " << endl; show_items(y, 5); return 0; }
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 33 May 3, 2011

template <class T> void bubble_sort(T a[] , int size) { int i, j; T temp; for (i = 0; i < size; i++) for (j = size-1; i<j; j--) if (a[j] < a[j-1]) { temp = a[j-1]; a[j-1] = a[j]; a[j] = temp; } } template <class X> void show_items(X a[], int size) { int i; for(i=0; i < size; i++) cout << a[i] << ", "; cout << endl; }
Dr K.Srinivas Object Oriented Programming Systems 34

Function Template with multiple parameters


The general form of a template function definition is as follows Template <class T1, class T2, .> returntype functionname (parameter list of types T1,T2,.) { // body of function }
Dr K.Srinivas Object Oriented Programming Systems

Function Template with multiple parameters


#include <iostream> using namespace std; template <class type1, class type2> void myfunc(type1 x, type2 y) { cout << x << ' ' << y << endl; } int main() { myfunc(10, "hi"); myfunc(0.23, 10L); return 0; }
Dr K.Srinivas Object Oriented Programming Systems

May 3, 2011

35

May 3, 2011

36

Overloading of Template Functions


A template function may overloaded either by template function or ordinary function of its name The overloading resolution is accomplished as follows
1.

Overloading of Template Functions


Template<class T> void display(T x) { cout<<Template display:<<x<<\n; } Void display(int x) { cout<<Explicit display:<<x<<\n; } Int main() { display(10); display(14.34); display(c); return 0; }
37 May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 38

Call an ordinary function that has an exact match Call a template function that could be created with an exact match Try normal overloading resolution to ordinary functions and call the one that matches
Dr K.Srinivas Object Oriented Programming Systems

2.

3.

May 3, 2011

Explicitly Overloading a generic Functions


// Overriding a template function. #include <iostream> using namespace std; template <class X> void swapargs(X &a, X &b) { X temp; temp = a; a = b; b = temp; }
// This overrides the generic version of swap().

Explicitly Overloading a Generic Functions


int main() { int i=10, j=20; float x=10.1, y=23.3; char a='x', b='z'; cout << "Original i, j: " << i << ' ' << j << endl; cout << "Original x, y: " << x << ' ' << y << endl; cout << "Original a, b: " << a << ' ' << b << endl; swapargs(i, j); // this calls the explicitly overloaded swapargs() swapargs(x, y); // swap floats swapargs(a, b); // swap chars cout << "Swapped i, j: " << i << ' ' << j << endl; cout << "Swapped x, y: " << x << ' ' << y << endl; cout << "Swapped a, b: " << a << ' ' << b << endl; return 0; }

void swapargs(int &a, int &b) { int temp; temp = a; a = b; b = temp; cout << "Inside overloaded swapargs(int &, int &).\n"; }

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

39

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

40

10

Overloading a Function Template


// Overload a function template declaration. #include <iostream> using namespace std; // First version of f() template. template <class X> void f(X a) { cout << "Inside f(X a)\n a = " << a << endl; } // Second version of f() template. template <class X, class Y> void f(X a, Y b) { cout << "Inside f(X a, Y b)\n a = " << a << "\n b = " << b << endl; } int main() { f(10); // calls f(X) f(10, 20); // calls f(X, Y) return 0; }
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 41

Class Templates
Class templates Allow type-specific versions of generic classes Format: template <class T>class className { definition } Need not use "T", any identifier will work To create an specific object of that class, using the following syntax: ClassName< type > myObject; Ex: Stack< double > doubleStack;
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 42

Generic Stack Class


// Demonstrate a generic stack class. #include <iostream> using namespace std; const int SIZE = 100; // This creates the generic class stack. template <class SType> class stack { SType stck[SIZE]; int tos; public: stack(); ~stack(); void push(SType i); SType pop(); };
Dr K.Srinivas Object Oriented Programming Systems

Generic Stack Class


// stack's constructor function. template <class SType> stack<SType>::stack() { tos = 0; cout << "Stack Initialized\n"; } /* stack's destructor function. This function is not required. It is included for illustration only. */ template <class SType> stack<SType>::~stack() { cout << "Stack Destroyed\n"; }

May 3, 2011

43

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

44

11

Generic Stack Class


/ Push an object onto the stack. template <class SType> void stack<SType>::push(SType i) { if(tos==SIZE) { cout << "Stack is full.\n"; return; } stck[tos] = i; tos++; } // Pop an object off the stack. template <class SType> SType stack<SType>::pop() { if(tos==0) { cout << "Stack underflow.\n"; return 0; } tos--; return stck[tos]; }
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 45

Generic Stack Class


int main() { stack<int> a; // create integer stack stack<double> b; // create a double stack stack<char> c; // create a character stack int i; // use the integer and double stacks a.push(1); b.push(99.3); a.push(2); b.push(-12.23); cout cout cout cout << << << << a.pop() << " "; a.pop() << " "; b.pop() << " "; b.pop() << "\n"; // demonstrate the character stack for(i=0; i<10; i++) c.push((char) 'A'+i); for(i=0; i<10; i++) cout << c.pop(); cout << "\n"; return 0; }

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

46

Class Template with multiple parameters


A template class can have more than one generic data type.
#include <iostream> using namespace std; template <class Type1, class Type2> class myclass { Type1 i; Type2 j; public: myclass(Type1 a, Type2 b) { i = a; j = b; } void show() { cout << i << ' ' << j << '\n'; } };
Dr K.Srinivas Object Oriented Programming Systems

Class Template with multiple parameters


int main() { myclass<int, double> ob1(10, 0.23); myclass<char, char *> ob2('X', "This is a test"); ob1.show(); // show int, double ob2.show(); // show char, char * return 0; }

May 3, 2011

47

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

48

12

Vector Class templates


template<class T> class vector { T * V; public: vector() { v= new T[szie]; for(int i=0;i<size;i++) v[i]=0;} vector(T * a) {for(int i=0;i<size;i++) v[i]=a[i];} T operator*(vector &y) { T sum =0; for(int i=0;i<size;i++) sum+=this->v[i]*y.v[i]; return sum; } };

Vector Class templates


const size = 3; int main() { int x[3]={123}; int y[3]={4,5,6}; vector <int> v1; vector <int> v2; v1=x; v2=y; int r=v1*v2; cout<<r=<<r<<\n; float x1[3]={1.1.,1.2,1.3}; float y1[3]={2.1,2.2,2.3}; vector <float> v3; vector <float> v4; v3=x1; v4=y1; int r2=v3*v4; cout<<r2=<<r2<<\n; return 0; }

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

49

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

50

Exception Handling
Errors are two types: Logic and syntax errors. Exceptions are errors or some peculiar problems other than logic or syntax errors. Exceptions are two kinds: Synchronous and asynchronous Synchronous: Errors related to programming i.e Out-of range index, over-flow, divided by zero and etc. Asynchronous: Errors beyond the control of the program such as keyboard interrupts. Exceptions are runtime anomalies or unusual conditions that a program may encounter while executing.

Exception Handling

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

51

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

52

13

Basics of Exception Handling


The mechanism has error handling code that perform the following tasks: Find the problem ( Hit the exception ) Inform that an error has occurred ( Throw the exception ) Receive the error information ( Catch the exception ) Take corrective actions ( Handle the exception )
Dr K.Srinivas Object Oriented Programming Systems

Exception Handling Mechanism


The error handling code basically consists of two segments: One to detect errors and to throw exceptions Other to catch the exceptions and to take appropriate actions. The catch block catches an exception must immediately follow the try block that thorws the exception.

May 3, 2011

53

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

54

Exception Handling Mechanism


The general form of try and catch blocks are as follows:
try { ............ .. throw exception; . } catch(type org) { ............ .. .. } .
May 3, 2011

Try Block
The try block contains portion of program or 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. The try block is immediately followed by the catch block.

try block
Detects and throws an exception Exception Object

catch block
catches and handles the exceptions

Dr K.Srinivas Object Oriented Programming Systems

55

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

56

14

Throwing an Exception
throw - indicates an exception has occurred
usually has one operand (sometimes zero) of any type if operand an object, called an exception object conditional expression can be thrown code referenced in a try block can throw an exception exception caught by closest exception handler control exits current try block and goes to catch handler (if it exists) Example (inside function definition): if ( denominator == 0 ) throw DivideByZeroException(); throws a DivideByZeroException object
Dr K.Srinivas Object Oriented Programming Systems

Catching an Exception
Exception handlers are in catch blocks
Format: catch( exceptionType parameterName){
exception handling code } caught if argument type matches throw type if not caught then terminate called which (by default) calls abort

Example:
catch ( DivideByZeroException ex) { cout << "Exception occurred: " << ex.what() <<'\n' } catches exceptions of type DivideByZeroException

Catch all exceptions catch(...) - catches all exceptions


57 May 3, 2011

May 3, 2011

you do not know what Dr K.Srinivas exception occurred type of Object Oriented Programming Systems there is no parameter name - cannot reference the object

58

Benefits of exception handling


separates of error handling from normal processing provides a systematic way to report and handle exceptional situations (failures or errors) deals with synchronous errors (i.e., divide by zero) exceptions are necessary for making reusable libraries and components work Exception handling another way to return control from a function or block of code It makes clear, robust, fault-tolerant programs useful when program cannot recover but must shut down cleanly
Dr K.Srinivas Object Oriented Programming Systems Dr K.Srinivas Object Oriented Programming Systems

May 3, 2011

59

May 3, 2011

60

15

Function invoked by try block throwing exception


throw block Throwing Mechanism throw (exception); throw exception; throw
Throw Exception function that causes an exception Invoke function

Invoking function that generates exception


#include<iostream> using namespace std; void divide(int x, int y, intz) { cout<<"\n We are inside the function \n"; if((x-y)!= 0) //It is ok { int R =z/(x-y); cout<<"Result=" <<R<<"\n"; } else //There is a problem { throw(x-y); //Throw point } }
61 May 3, 2011

int main() { Try { cout<<"We are inside the try block \n"; divide(10,20,30); //Invoke divide() divide(10,10,20); //Invoke divide() } catch(int i) //Catches the exception { cout<<"Caught the exception \n"; } return 0; }

try block
Invoke a function that contains an exception

catch block
catches and handles the exceptions

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

Dr K.Srinivas Object Oriented Programming Systems

62

Multiple catch statements


try { //try block } catch(type1 arg) { // catch block1 } catch(type2 arg) { // catch block2 } .. catch(typeN arg) { // catch blockN }
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 63

Multiple catch statements


#include <iostream> using namespace std; void f(int test) { try{ if(test) throw test; // throw int else throw "Value is zero"; // throw char * } catch(int i) { cout << "Caught One! Ex. #: " << i << '\n'; } catch(char *str) { cout << "Caught a string: "; cout << str << '\n'; } }
May 3, 2011

int main() { cout << "start\n"; f(1); f(2); f(0); f(3); cout << "end"; return 0; }
64

Dr K.Srinivas Object Oriented Programming Systems

16

Catching Class Types


An Exception can be of any type, including class types that you create. Most exceptions will be class types rather than built-in types.
#include <iostream> #include <cstring> using namespace std; class MyException { public: char str[80]; int what;

Catching Class Types


int main() { int i; try { cout << "Enter a positive number: "; cin >> i; if(i<0) throw MyException("Not Positive", i); } catch (MyException e) { // catch an error cout << e.str << ": "; cout << e.what << "\n"; } return 0; }
66

MyException() { *str= 0; what = 0; } MyException(char *s, int e) { strcpy(str, s); what = e; } };

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

65

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

Exception Specifications
To restrict a function to throw only certain specified exceptions. This is achieved by adding a throw list clause to the function definition. Syntax is: type function( arg-list ) throw ( type-list ) { // function body } type-list specifies the type of exception that may thrown. if other type thrown, function unexpected called throw() (i.e., no throw list) states that function will not throw any exceptions
in reality, function can still throw exceptions, but calls unexpected (more later)
Dr K.Srinivas Object Oriented Programming Systems

Exception Specifications/ Restricting Exceptions


// Restricting function throw types. #include <iostream> using namespace std; // This function can only throw ints, chars, and doubles. void Xhandler(int test) throw(int, char, double) { if(test==0) throw test; // throw int if(test==1) throw 'a'; // throw char if(test==2) throw 123.23; // throw double } int main() { cout << "start\n"; try{ Xhandler(0); } catch(int i) { cout << "Caught an integer\n"; } catch(char c) { cout << "Caught char\n"; } catch(double d) { cout << "Caught double\n"; } cout << "end"; return 0; }
68

May 3, 2011

67

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

17

Catching all Exceptions


In some circumstances you want an exception handler to catch all exception instead of just a certain type. This is achieved through catch. Syntax is: Catch() { // process all exceptions }
#include <iostream> using namespace std;

Catches all exceptions.


int main() { cout << "Start\n"; Xhandler(0); Xhandler(1); Xhandler(2); cout << "End"; return 0; }

void Xhandler(int test) { try{ if(test==0) throw test; // throw int if(test==1) throw 'a'; // throw char if(test==2) throw 123.23; // throw double } catch(...) { // catch all exceptions cout << "Caught One!\n"; } }

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

69

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

70

Rethrowing an exception
Rethrowing exceptions
used when an exception handler cannot process an exception rethrow exception with the statement: throw;
no arguments
include <iostream> using namespace std; void divide(double x, double y) { try { if(y==0.0) throw y; else cout<<Division=<<x/y<<\n; } catch(double) { cout <<Caught double inside function\n; throw; //rethrow double } cout<<End of function \n; }

int main() { cout<< Inside main; try { divide(10.5,2.0); divide(20.0,0.0); } catch(double) { cout <<Caught double insideMain\n; } cout << Main end; return 0; }

This causes the current exception to be thrown to the next enclosing try/catch sequence handler can always rethrow exception, even if it performed some processing

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

71

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

72

18

Rethrowing an exception
#include <iostream> using namespace std; void Xhandler() { try { throw "hello"; // throw a char * } catch(char *) { // catch a char * cout << "Caught char * inside Xhandler\n"; throw ; // rethrow char * out of function } } int main() { cout << "Start\n"; try{ Xhandler(); } catch(char *) { cout << "Caught char * inside main\n"; } cout << "End"; return 0; }

Stack Unwinding
The automatic variables declared in the try bock will be destroyed when an exception is thrown When an exception is thrown, control passes from a try block to a handler, the C++ run time calls destructors for all automatic objects constructed since the beginning of the try block. This process is called stack unwinding. The automatic objects are destroyed in reverse order of their construction. If during stack unwinding a destructor throws an exception and that exception is not handled, the terminate() function is called

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

73

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

74

Design Issues
How and where are exception handlers specified and what is their scope? How is an exception occurrence bound to an exception handler? Where does execution continue, if at all, after an exception handler completes its execution? How are user-defined exceptions specified?

Design Issues
Should there be default exception handlers for programs that do not provide their own? Can built-in exceptions be explicitly raised? Are hardware-detectable errors treated as exceptions that can be handled? Are there any built-in exceptions? How can exceptions be disabled, if at all?

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

75

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

76

19

Standard Library Exception Hierarchy Exceptions fall into categories


hierarchy of exception classes base class exception (header <exception>)
function what() issues appropriate error message

Standard Library Exception Hierarchy cont class runtime_error


errors detected at execution time Derived classes:
overflow_error - arithmetic overflow underflow_error - arithmetic underflow

derived classes: runtime_error and logic_error (header <stdexcept>)

Class logic_error
errors in program logic, can be prevented by writing proper code Derived classes:
invalid_argument - invalid argument passed to function length_error - length larger than maximum size allowed was used out_of_range - out of range subscript
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 77 May 3, 2011

other classes derived from exception


exceptions thrown by C++ language features
new - bad_alloc dynamic_cast - bad_cast (Chapter 21) typeid - bad_typeid (Chapter 21)

put std::bad_exception in throw list


unexpected() will throw bad_exception instead of calling function set by set_unexpected

Dr K.Srinivas Object Oriented Programming Systems

78

Const member functions


Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called. To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. The const keyword is required in both the declaration and the definition. A const object may not invoke a non-const member function. A const member function can be called by either const or nonconst objects. A constant member function cannot modify any data members.
Dr K.Srinivas Object Oriented Programming Systems

Miscellaneous C+ + topics

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

79

May 3, 2011

80

20

Const member functions


/* Demonstrate const member functions. This program won't compile. */

Mutable
A constant member function cannot modify any data members except mutable data memeber A mutable member can be modified by a const member function.

void seti(int x) const { i = x; // error! } }; int main() { Demo ob; ob.seti(1900); cout << ob.geti(); return 0; }

#include <iostream> using namespace std; class Demo { int i; public: int geti() const { return i; // ok }
May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

81

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

82

Const member functions


// Demonstrate mutable.

Volatile Member Functions


Class member functions may be declared as volatile, which causes this to be treated as a volatile pointer. A volatile object can only call volatile member functions. Ex:

#include <iostream> using namespace std; class Demo { mutable int i; int j; public: int geti() const { return i; // ok }

void seti(int x) const { i = x; // error! } }; int main() { Demo ob; ob.seti(1900); cout << ob.geti(); return 0; }

class X { public: void f2(int a) volatile; // volatile member function };

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

83

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

84

21

Using the asm keyword


Embed assembly language directly into your program by using asm keyword. The asm keyword has three slightly different general forms 1. asm instruction; 2. asm instruction newline 3. asm { instruction sequence } Here instruction is any valid assembly language instruction. Unlike any other c++ builder statement, an asm statement does not have to end with a semicolon; It can end with either a semicolon or a newline
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 85 May 3, 2011

Linkage Specification
By using linkage specification, you can cause a function to be linked as a different type of language function. The term "linkage specification" refers to the protocol for linking functions (or procedures) written in different languages. The general format is: extern language function-prototype; Linkage specification must be global. It cannot be used inside a function. The keyword extern is a necessary part of the linkage specification.

Dr K.Srinivas Object Oriented Programming Systems

86

Linkage Specification
#include <iostream> using namespace std; extern "C" void myCfunc(void); int main() { myCfunc(); return 0; } // This will link as a C function. void myCfunc(void) { cout << "This links as a C function.\n"; }
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 87 May 3, 2011

The .* and ->* operators


The .* and ->* are called pointer-to-member operators. Allow you to point to a member of a class, rather than to a specific instance of that member with that some object. If you are accessing a member of an object using an object or a reference with .* operator. If you are accessing a pointer to the object, use the ->* operator.

Dr K.Srinivas Object Oriented Programming Systems

88

22

The .* and ->* operators


#include <iostream> using namespace std; class myclass { public: int sum; void myclass::sum_it(int x); }; void myclass::sum_it(int x) { int i; sum = 0; for(i=x; i; i--) sum += i; }
May 3, 2011

Granting Access
When a base class is inherited as private, all public and protected members of that class become private members of the derived class. In certain circumstances, you may want to restore one or more inherited members to their original access specifications. Two ways to accomplish this. 1. using statement it support namespacess 2. An access declaration syntax is : base-class::member;
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 90

int main() { int myclass::*dp; // pointer to an integer class member void (myclass::*fp)(int x); // pointer to member function myclass c1, *c2,d; c2=&d; dp = &myclass::sum; // get address of data fp = &myclass::sum_it; // get address of function (c1.*fp)(7); // compute summation of 7 cout << "summation of 7 is " << c1.*dp; (c2->*fp)(7); // compute summation of 7 cout << "summation of 7 is " << c2->*dp; return 0; }

Dr K.Srinivas Object Oriented Programming Systems

89

Granting Access
#include <iostream> using namespace std; class base { int i; // private to base public: int j, k; void seti(int x) { i = x; } int geti() { return i; } };
// Inherit base as private. class derived: private base { public:
/* The next three statements override base's inheritance as private and restore j, seti(), and geti() to public access. */

Namespace
Namespaces allow to group entities like classes, objects and functions under a name. The namespace keyword allows you to partition the global namespace by creating a declarative region. Syntax is:
namespace name { // declaration } Difference between namesapce and class definition is namespace concluded with a closing brace but no terminating semicolon

base::j; // make j public again - but not k base::seti; // make seti() public base::geti; // make geti() public
// base::i; // illegal, you cannot elevate access

int a; // public };

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

91

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

92

23

Namespace
Ex:
namespace Testspace { int m; void display(int n) { cout<<n; } }

Namespace
This approach is cumbersome , if the members of a namespace are frequently used

In such case , we can use a using directive to simplify their access. Syntax is
using namespcae namespacename; or using namespace::membername; using namespace Testspace; using Testspace::m; m=100 m=100; display(200); display(200); //not ok, display not
visible

If You want to assign a value to m, use the scope resolution operator Testspace::m=10; This approach is cumbersome , if the members of a namespace are frequently used
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 93

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

94

unnamed namespace
A namespace with no identifier/name before an opening brace produces an unnamed namespace. Unnamed namespace members occupy global scope and are accessible in all scopes following the declaration in the file We can access them without using any qualifier. A common use of unnamed namespace is to shield global data from potential name classes between files. Every file has its own, unique unnamed namespace.
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 95

unnamed namespace
namespace name1 { double x=4.56; int m=100; namespace name2 { double y=1.23; } } namespace { int m=200; }
May 3, 2011

int main() { cout<<"X="<<name1::X<<"\n"; cout<<"m="<<name1::m<<"\n"; cout<<"y="<<name1::name2::y<<"\n"; cout<<"m="<<m<<"\n"; return 0; }

Dr K.Srinivas Object Oriented Programming Systems

96

24

The std Namespace


C++ defines its entire library in its own namespace called std; This is the reason that most of the c++ programs include the following statement
using namespace std;

The std Namespace


You can also explicitly qualify each name with std:: #include <iostream> int main() { int val; std::cout << "Enter a number: "; std::cin >> val; std::cout << "This is your number: "; std::cout << std::hex << val; return 0; }
97 May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 98

This causes the std namespace to be brought into the current namespace It gives you direct access to the names of the functions and classes defined within the library without having to qualify each one with std:: You can also explicitly qualify each name with std::
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems

Explicit constructors
The keyword explicit is used to create noncoverting constructors.
class MyClass { int i; public: MyClass(int j) {i = j;} // ... }; MyClass ob1(1); MyClass ob2 = 10;
MyClass ob2 = 10; is automatically converted into the form MyClass ob2(10);
May 3, 2011 Dr K.Srinivas Object Oriented Programming Systems 99 May 3, 2011

Explicit constructors
By declaring MyClass constructor as explicit, this automatic conversion will not be supplied. class MyClass { int i; public: explicit MyClass(int j) {i = j;} // ... }; Now only constructors of the form MyClass ob(110);

Dr K.Srinivas Object Oriented Programming Systems

100

25

typename and export


1.

Typename:
Recently, two keywords were added to c++ that relate specifically to template: typename and export The typename keyword has two uses. 1. It can be substituted for the keyword class in a template declaration
template <typename X> void swapargs(X &a, X &b) { X temp; temp = a; a = b; b = temp; } typename specifies the generic type X, There is no difference between using class and using typename in this context Dr K.Srinivas

2. The second use of typename is to inform the compiler that a name used in a template declaration is a type name rather than an object name. 2. export
The export keyword can precede a template declaration.

May 3, 2011

Object Oriented Programming Systems

101

May 3, 2011

Dr K.Srinivas Object Oriented Programming Systems

102

26

Das könnte Ihnen auch gefallen