Unit 3 and 4
Unit 3 and 4
Unit 3 and 4
File I/O
May 3, 2011
May 3, 2011
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.
Disk
Result File
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 );
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
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
May 3, 2011
May 3, 2011
11
May 3, 2011
12
14
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
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
17
May 3, 2011
18
May 3, 2011
19
May 3, 2011
20
May 3, 2011
21
May 3, 2011
22
File Pointer
Input Pointer (get pointer)
The input pointer is used for reading contents of 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
seekp( )
tellg( )
tellp( )
May 3, 2011
May 3, 2011
26
start of the file current position of the pointer end of the file
Dr K.Srinivas Object Oriented Programming Systems 27
May 3, 2011
28
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
#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
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
May 3, 2011
35
May 3, 2011
36
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
void swapargs(int &a, int &b) { int temp; temp = a; a = b; b = temp; cout << "Inside overloaded swapargs(int &, int &).\n"; }
May 3, 2011
39
May 3, 2011
40
10
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
May 3, 2011
43
May 3, 2011
44
11
May 3, 2011
46
May 3, 2011
47
May 3, 2011
48
12
May 3, 2011
49
May 3, 2011
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
51
May 3, 2011
52
13
May 3, 2011
53
May 3, 2011
54
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
55
May 3, 2011
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
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
May 3, 2011
59
May 3, 2011
60
15
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
62
int main() { cout << "start\n"; f(1); f(2); f(0); f(3); cout << "end"; return 0; }
64
16
May 3, 2011
65
May 3, 2011
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
May 3, 2011
67
May 3, 2011
17
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
69
May 3, 2011
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
71
May 3, 2011
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
73
May 3, 2011
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
75
May 3, 2011
76
19
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
78
Miscellaneous C+ + topics
May 3, 2011
79
May 3, 2011
80
20
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
81
May 3, 2011
82
#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; }
May 3, 2011
83
May 3, 2011
84
21
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.
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
88
22
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; }
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
91
May 3, 2011
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
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
96
24
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);
100
25
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
101
May 3, 2011
102
26