PDS 2 Unit 3 Notes



Comments



Description

WWW.VIDYARTHIPLUS.COM UNIT III C++ PROGRAMMING ADVANCED FEATURES Abstract class – Exception handling - Standard libraries - Generic Programming - templates – class template - function template – STL – containers – iterators – function adaptors – allocators Parameterizing the class - File handling concepts. 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. WITHOUT EXCEPTION HANDLING – WITH EXCEPTION HANDLING When an exception occurs, control goes to the operating system, where typically • an error message is displayed • the program is terminated – – Programs are allowed to trap exceptions There is a possibility to fix the problem and continuing execution Exception handling mechanism To detect and report error The error handling code performs the following task 1. Find the problem (Hit the exception) 2. Inform that an error has occurred.(Throw the exception) 3. Receive the error information.(Catch the exception) 4. Take corrective actions(Handle the exception) . Keywords in Exception Handling 1. try 2.throw 3. catch WWW.VIDYARTHIPLUS.COM 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. Exception Handling Syntax: try //try block { ……. throw exception; // Block of statements which ……. // detects and throws an exception } catch(type arg) // Catches exception { ……. …….. // Block of statements that …….. // handles the exception } EG: #include <iostream> WWW.VIDYARTHIPLUS.COM V+ TEAM j. j=0. try { // start a try block cout << Inside try block\n”. cout << “End”. cout << i . } } Exception Types  – –  – Synchronous Exception: Out of rage Over flow Asynchronous Exception -Error that are caused beyond the control of the program Keyboard interrupts In C++ only synchronous exception can be handled. WWW. return 0. i=10.VIDYARTHIPLUS.COM V+ TEAM . cout << "Starts here\n". // throw an error cout << “This will not execute”. } catch (int i) { // catch an error cout << “caught an exception “.h> int main() { int i. throw 100.COM int main() cout << “start”. Factors determining Exception – – – Division by zero Access to an array outside of its bounds Running out of memory – Running out of disk space    Need for Exception Handling Dividing the error handling Unconditional termination & programmer preferred termination Separating error reporting and error handling  Object destroy problem #include<iostream.WWW.VIDYARTHIPLUS. return 0. cout << "Starts here\n". i=10.COM if(j==0) { cout<<”RESULT IS “<<i/j.j. try { // start a try block cout << "Inside try block\n". Once the exception is thrown the catch block catches the value (here zero) and handles it. After that the program continues it normal execution. j=0. Functions Generating Exceptions • • C++ allows functions to generate exceptions.h> int main() { int i. // throw an error cout << "This will not be printed \n". if(j==0) { throw j. cout << a << "\n". } else return 0. Enclose the function call with a try catch block syntax: try { function(arg).VIDYARTHIPLUS. } cout<<”RESULT IS “<<i/j. } • • • • • catch( int a) { // catch an error cout << "The Number Caught is : ".WWW. These functions cannot be called as an ordinary function. } cout << "Ends here". } When the program enters the try block it is said to be in the guarded section. } #include<iostream.VIDYARTHIPLUS.COM V+ TEAM . 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. } catch(type arg) { WWW. The throw statement will have the following EG: form – throw (exception) – throw exception -.h> void compute(int a. } cout<<”RESULT OF THE DIVISION”<<c. syntax: try { any statements if (some condition) throw value1. arg will receive its value Multiple Catch Statements • • A try can have multiple catches if there are multiple catches for a try. else c=a/b. cin>>x>y. which is passed as an argument to the exception handler.VIDYARTHIPLUS. EX: throw b. only one of the matching catch is selected and that corresponding catch block is executed. When an exception is caught.throw Catching Mechanisms • • if the data type specified by a catch.COM V+ TEAM . // fun generating exception }catch(int k) { cout<<”DIVIDE BY ZERO EXCEPTION”<<endl. try { compute(x/y).COM -----} #include<iostream. then catch statement is executed.VIDYARTHIPLUS.WWW. if(b==0) { throw b. } catch (type1 name) WWW. else if (some other condition) throw value2. } } Throwing Mechanisms • • • An exception is thrown by using the throw keyword from inside the try block. A throw expression accepts one parameter. cout<<”ENTER TWO NUMBERS”. matches that of the exception. } void main() { int x. else if (some last condition) throw valueN.y.int b) { int c. COM V+ TEAM . } catch(char c) { cout<<”Character value is thrown” <<c. } } void main() { cout<<”Main Program”<<endl. else if (value==1) //throw a char throw ‘a’.COM { any statements } catch (type2 name) { any statements } catch (typeN name) { any statements } eg: #include<iostream.VIDYARTHIPLUS.VIDYARTHIPLUS.WWW. multiple_catch(1). multiple_catch(5).1. } catch(int i) { cout<<”Integer value is thrown”<<i.h> void multiple_catch(int value) { try { if (value==0) //throw an int value throw 1. else //throw float throw 1. } catch(float f) { cout<<”Float value is thrown”<<f. multiple_catch(0). } Rethrowing Exceptions WWW. } catch (char c) { throw. } void shoex() { cout<<”error no:”<<exno. case 4: throw “welcome”.h> class sam{ into erno. cin>>c.VIDYARTHIPLUS.COM syntax: try { …. } catch (int ie) { cout<<”ie”<<ie. //rethrowing } catch (char ce) { cout <<”ce”<<ce. public: sam (int errno){ exno=errno.VIDYARTHIPLUS. case 2: throw ‘a’. void ergen(){ try{ sam s1(20).COM V+ TEAM . } //rethrow same exception in catch block in main() eg: #include <iostream. throw.WWW. switch (c) { case 1: throw 10. } }.. int c. case 3: throw s1. WWW. throw a. show x(). a function unexpected () is called. throw 0.COM V+ TEAM .VIDYARTHIPLUS. } catch(char) { cout<<”caught char”. // throws char (not in exception-specification) } int main (void) { WWW. Unexpected Function • if a function throws an exception which is not allowed. } catch (int) { cout <<”caught integer”.COM throw. which in turn calls abort. eg: #include <iostream> void myunexpected () { cout << "unexpected called\n". • We can use set_unexpected in a similar to set_terminate Syntax: set_unexcepted(my unexcepted).WWW. Syntax: set_terminate (myterminate). throw 10. } } 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.VIDYARTHIPLUS. } catch (sam s2){ s2. // throws int (in exception-specification) } void myfunction () throw (int) { throw 'x'. //rethrowing } } void main (){ try{ ergen(). void main() { WWW.COM V+ TEAM .. Example: template<typename T> class MyContainer { // Container that deals with an arbitrary type T }.WWW. 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.) { cout << "caught some other exception type\n".VIDYARTHIPLUS. floats. • Once caught. 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. } Uncaught Exception() • This function returns true if an exception has been thrown but not yet caught. The simplest example for generic programming are container classes like arrays. 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. But there's much more to generic programming.VIDYARTHIPLUS. } catch (. try { myfunction().. lists or maps that contain a collection of other objects. Syntax: bool uncaught_exceptions. } catch (int) { cout << "caught int\n".it means to write programs that are evaluated at compile time. In the context of C++ . the function returns false. and other types or deal with pointers to void and therefore losing all type information. } return 0.COM set_unexpected (myunexpected). When you instance the template later you tell the compiler which type it should use to create the class out of the template. } void putdata() { if(image>0) cout<<real<<"+"<<image<<"i". Member function.WWW.VIDYARTHIPLUS. public: void getdata() { cout<<"\n Enter the complex values". Example: #include<iostream. }. Syntax: template <class T> class <class_name> { Member.COM // Make MyContainer take just ints. MyContainer<int> intContainer. cin>>real>>image.h> #include<conio. } 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.VIDYARTHIPLUS. WWW.h> template <class T> class complex { T real .image.COM V+ TEAM . getch().VIDYARTHIPLUS. } }.COM V+ TEAM . The data type is not specified while declaring the function It performs appropriate operation depending on the data type we passed to them . } FRIEND OF CLASS TEMPLTAES A friend of a class template can be one of the following:  Class template  Function template  Non-template function  Non-template class  A specialization of class template  A specialization of function template Function Template The template declared for function are function template Function templates are generic function.j<5.putdata(). Syntax: Template<typename T .i<5.getdata(). obj1.putdata(). void main() { clrscr().…. complex <float> obj2.WWW.COM else cout<<real<<image<"i". complex <int> obj1.j++) { If(TempGenericArray[i]<TempGenericArray[j]) { WWW.> 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++) { For( int j=i+1.VIDYARTHIPLUS. obj1. which work for any data that is passed to them . obj2.getdata(). obj2. class T2> void display(T1 a.WWW. // calling function template 2 } Sample output: 6 6 4 2 1 S k f d a 9. } } } } Template <class T> Void Generic Display(T TempGenericArray[]) // template function2 { Cout<<“\n”.0. TempGenericArray[i]=TempGenericArray[j].9.VIDYARTHIPLUS. GenaricBubbleSort(Array2) //calling function template 1 Generic Display(Array 2).0.5.5 0.5).4.2. For(int i=0.6.VIDYARTHIPLUS.COM V+ TEAM . // calling function template 1 GenericBubbleSort( Array3 ). } WWW.i++) { Cout<<TempGenericArray[i]<<“\t”. GenericBubble Sort (Array 3).5 Function templates with multiple arguments Function templates can have different data type to represent the parameters.h> template <class T1.2.4 7 5.5.4.h> #include<conio. Syntax: template <class T1. }} Void main() { int Array1[]={1.class T2> return_type function_name(arguments) { <function body> } Example: #include<iostream. Foat Array3[]={ 7.i<5.6} GenericBubbleSort(Array 1).2 2.COM int temp=TempGenericArray[i]. // calling function template 2 Char Array2[]=“sdfla”.T2 b) { cout<<a<<"\n"<<b<<"\n".2. //calling function template 1 GenericDisplay(Array2). TempGenericArray[j]=temp. //void display(T1. The destination stream that receives output from the program is called the output stream. Streams provide consistent interface for providing independence from having different operations for different IO devices.COM V+ TEAM .VIDYARTHIPLUS. (refer diagram in notebook) C++ STREAM CLASSES: (Refer diagram in notebook) Ios :    it is the base class for istream and ostream.5.75. It provides the basic support for formatted and unformatted I/O operations.COM void main() { clrscr(). This model is known as the inclusion compilation model. display("sample". The models are  Inclusion compilation model  Separate compilation model Inclusion compilation model It is possible to compile the template spread across multiple files by having the copy of the template text in all the files . the models the definitions from the source files are made available to the compiler. Separate compilation model It is possible to compile template separately and then use them by providing their prototype in other files . display(10.10.VIDYARTHIPLUS.2). It is declared as the virtual base class.256).T2). getch() } TEMPLATE COMPILATION MODELS Standard C++ defines two models for compiling template code. display(7.WWW.20). Istream: WWW. In each of these models. class declarations and function declarations are placed in header files and functions and member from the source files are made available to the compiler. The source stream that provides data to the program is called the input stream. Standard library functions STREAMS AND FORMATTED I/O :     A stream is a sequence of bytes (or) conceptually pipe like constructs used for providing I/O. display(10.this model is known as the separate compilation model."program"). COM    Provides facilities for formatted and unformatted input operations. Overloaded operators >> and << :   The >> operator is overloaded in the istream.  the input data are separated by white spaces and should match the type of variable in ‘cin’ . Void get(char) WWW. Putc() and write() functions are declared.getline(). istream and ostream through multiple inheritance. Acts as a base class for filebuf class. The getc() function has two different versions : 1. Provides an interface to physical devices through buffers.   cout<<variable 1<<….WWW. EXAMPLE : #include<iostream. Iostream:   Provides facilities for handling both input and output streams. Overloaded insertion operator (<<) Streambuf:    It is used to access streams using lower level functions. cin>>a. cout<<”The value of a is”<<a. The << operator is overloaded in the ostream. cout<<”Enter a variable”. } Putc() and getc() functions :   getc() and putc() are used for reading and writing to the streams.<<variable n. Functions such as getc().COM 2. Overloaded extraction operator (>>) Ostream:    Provides the facilities for formatted and unformatted output operations.VIDYARTHIPLUS. this statement is used for displaying data on the screen.>>variable n .  UNFORMATTED I/O OPERATIONS: 1. char get(void) V+ TEAM .read() are declared.VIDYARTHIPLUS. Inherits the properties of ios. cin>>variable 1>>….h> void main() { int a. int size).put(c). The prototypes for these three functions are : o o o    cin.get(c).getline(msg. The getline() also stops reading from input if end of file is specified.write(msg.get(c). Cin.COM   The put() function is used to display the data. Count++.read and write functions :   These functions are used for reading and writing strings. WWW.read(msg.h> void main() { char msg[100]. Get() reads a character at a time from the input stream and put() writes a character at a time to the output stream. while(c!=’\n’) { Cout.VIDYARTHIPLUS. Cin. int size). Cin. int size).100).getline(string variable .h> #include<conio. Example : #include<iostream.VIDYARTHIPLUS. cin.h> Void main () { Int count=0.10). cin. } Cout<<”\n Number of characters = “<<count. cin.read(string variable.write(string variable.WWW. } Getline . Cout.h> #include<conio.COM V+ TEAM . cout<<”Enter a text”. 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. Char c. Example: #include<iostream.5). read() stops only when end of file (ctrl + z ) is encountered . Cout<<1.’). unsetf(): -It provides undo operation for the above mentioned operations.fill(‘. -it is used in aligning vertical columns. 4. scientific notation .precision(3). 2.setf() : Example : #include<iostream. -The function specifies format flags that control output display like left (or) riight or right justification . Cout<<n. padding .h> #include<conio.width(10).n<=b.width(5). } WWW. Cout.VIDYARTHIPLUS.5).WWW.COM V+ TEAM . For(n=1.h> Void main () { Int n.0/float(n)<<”\n”. 3.n++) { Cout. 5. -default precision is six digits after the decimal point.fill() : .VIDYARTHIPLUS. Cout.width() : . If(n>3) Cout.specifies the character for filling up the unused portion of field. } Output: Object Objec getline() Object ( ctrl + z ) objec read()  FORMATTED I/O OPERATIONS : Built-in ios functions : 1.precision() : -it specifies the precision of the floating point number.write(msg. displaying base number.fill(‘*’). -it is used with width() . Cout.it specifies the width for display.COM Cout. VIDYARTHIPLUS.h> #include<iomanip> int main() ( cout<<setw(15)<<setiosflags(ios::left)<<setiosflags(ios::fixed)<<setprecision(2)<<setiosflags(ios::showpoi nt). cout<<setw(15)<<3<<setw(15)<<"Steffi"<<setw(10)<<setprecision(2)<<290.00<<endl.COM Cout.00<<endl. and also to get scientific notations for finding floating point variables . Cout<<12.75<<endl.h files WWW.width(15).50<<endl.VIDYARTHIPLUS. They need iostream. cout<<setw(15)<<1<<setw(15)<<"Lara"<<setw(10)<<setprecision(2)<<355. cout<<setw(15)<<4<<setw(15)<<"Jaspal"<<setw(10)<<setprecision(2)<<295. MANIPULATORS : Manipulators are special functions for formatting.WWW.h and iomanip. Manipulators are easy to write and produce more readable codes and make the program short. width() is used for right justification. Cout. cout<<"Roll Number"<<setw(15)<<"Name"<<setw(10)<<setprecision(2)<<"Marks"<<endl. we should use the setf() .345678.COM V+ TEAM . The choice between manipulators and ios functions to solve formatting problems sometimes depends on the preference of the user.fill(‘#’). cout<<setw(15)<<2<<setw(15)<<"Beckham"<<setw(10)<<setprecision(2)<<275. } Characteristics of manipulators:    Writing our own manipulators is possible.60<<endl. To get left justification . cout<<setw(15)<<5<<setw(15)<<"Parker"<<setw(10)<<setprecision(2)<<200. } Here . Manipulators : setw() setprecison() setfill() setiosflags() resetiosflags() ios functions : width() precision() fill() setf() unsetf() program #include<iostream. output /write only file fstream <file name > . The functions do not return the previous status. Binary streams: -binary values are inserted . Manipulating Files Opening Files : -files can be opened using two methods (i) using constructors (ii) using open functions Ifstream DisplayFile (“ Fewlines. -for output mode replace ifstream by ofstream.VIDYARTHIPLUS.COM    When a manipulator does not take any arguments . This is known as conversion.Text files are more general. It invokes a function from a standard library that comes with a C++ compiler .no conversion takes place. A C++ program does not directly request to the OS. when it is installed. Carriage return and Line Feed characters are inserted. Characteristics of ios functions:     they are single and cannot be combined to have multiple effects. FILE HANDLING INTRODUCTION: OS is the primary interface between the user and the computer.VIDYARTHIPLUS. (using constructors) -it is an ios::in (input mode). -in the above example fewlines is a physical file name.both input/read and output /write file. -the logical files will vanish when the program is over. 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. Displayfile is a logical file name. -if <enter> key is pressed. Binary files are not flexible. Dealing With Text Files Defining Files ifstream < filename> .WWW.h file ios functions are member functions. but physical files will be available in the OS. WWW. it is passed without the () parenthesis. The text stream files can be opened by any editor. Some manipulators are needed in pairs to produce the toggle effect. They need iostream. They are non-member-functions.read only file ofstream <filename> . The binary stream files are restricted to the application that creates the file.COM V+ TEAM .dat”). Text and Binary Files : Text stream: -deals with information which is in ASCII form. entryfile.VIDYARTHIPLUS. if(ch=='$') break. while(true) { cin>>inputline.dat"). cout<<outputline<<"\n".close().get(ch).VIDYARTHIPLUS. ofstream entryfile("fewlines.COM V+ TEAM . if(inputline =="end")break. ofstram entryfile("fewlines.outputline. cout<<"output:"<<endl.eof()) { displayfile>>outputline.dat”). } Using get () and put () #include<iostream> #include<fstream> #include<string> int main() { char ch.close(). return o. Closing Files -close () . } displatfile.open(“fewlines.COM Displayfile.to close a file -the allocated files are deallocated and flushed off when close () is invoked Using Text Files #include<iostream> #include<fstream> #include<string> int main() { string inputline. while(true) { cin.dat") cout<<"input:"<<endl. ifstream displayfile.WWW. entryfile<<ch. (using open function) Reading from and writing to files -use of overloaded << and>> operators are used to read from and write to a file. WWW. COM } entryfile. The read() and write() functions are performed object wise and not element wise. The first method uses a open().eof()) { displayfile. while(!displayfile. } displayfile. object_file.sizeof(<object>)).write((char*)&<the object>.file mode Ofstream Filename.close(). return 0. pipe(i) is used to add multiple modes.VIDYARTHIPLUS. Reading from and Writing To multiple files : object_file. ifstream displayfile("fewlines. -this is for reading from the file. file_name.dat”.WWW.sizeof(<object>)).open(“file. -this is for writing into the file.unsetf(ios::skipws). displayfile>>ch.COM V+ TEAM . The complete file can be read and written using these single statements.dat").open (“file. OR ifstream filename (“file. This is used by most of the users. } Dealing with binary files Opening a binary file : Open using a constructor with two arguments : -name of the file . ios::out |ios::binary|ios::trunc). The second method uses a constructor.read((char*)&<the object>. cout<<ch.close(). ios::in|ios::binary).dat”. Writing a file : ofstream file_name(“file_dat”. Closing Binary Files : WWW.dat”.ios::out|ios::binary|ios::trunc). filename . Or ifstream file_name.VIDYARTHIPLUS.ios::in|ios::binary). Example: #include"stdafx. or file_object. }r.VIDYARTHIPLUS.WWW. std::cin. (i) number of bytes to skip (ii) from where to skip seekp() to move put and write pointers. int i.std::ios::trunc|std::ios::in|std::ios::out|std::ios::binary).VIDYARTHIPLUS. name and an int\n". tellg() and tellp() : these pointers tell us where the read and write pointers of a file are pointing to. there are two types of file pointers to access a file in a random manner. it is possible to search any record of any file by skipping the other records inbetween. Program – pg – 567 RANDOM ACCESS : In C++ .6).close().getline(r.h" #include<iostream> #include<fstream> struct record { char code[6].dat". if(!file) { std::cout<<"unable to open file".close(). Using Binary Files : -fail() and eof() are used. -it deallocates the files and flushes the buffer.name. exit(0).20). std::cin.COM file_name. WWW.code. int main() { std::fstream file("Temp. char name[20]. tellg() tells us where the get pointer is pointing to. tellp() tells us where the put pointer is pointing to. } std::cout<<"enter character code. seekg() and seekp() : seekg() to move get or read pointer of file. 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 .COM V+ TEAM . It takes two arguments .getline(r. std::cout<<"\n\n"<<file.tellp().tellg()<<'\n'<<file.WWW. file.write((char *)&r.i. std::cout<<"\n\n"<<file.tellg()<<'\n'<<file.seekp(5).VIDYARTHIPLUS.COM V+ TEAM . std::cout<<"\n\n"<<file. file.tellp().seekg(3).COM std::cin>>r.tellp(). } WWW.VIDYARTHIPLUS.tellg()<<'\n'<<file.sizeof(r)). file.
Copyright © 2024 DOKUMEN.SITE Inc.