Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures
|
|
- Junior Ward
- 6 years ago
- Views:
Transcription
1 Lecture 10 Class string Exception Handling To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures Class template auto_ptr Lec 10 Programming in C++ 1 Class string Template class basic_string String manipulation (copying, searching, etc.) typedef basic_string< char > string; #include <string> using std::string string initialization string s1( "Hello" ); string s2( 8, 'x' ); 8 'x' characters string month = "March ; Implicitly calls constructor (not the assignment operator); Lec 10 Programming in C++ 2 1
2 string features Class string Not necessarily null terminated length member function: s1.length() Use [] to access individual characters: s1[0] 0 to length-1 string not a pointer Many member functions take start position and length Stream extraction White space delimited input. cin >> stringobject; getline(cin, s); Delimited by newline Lec 10 Programming in C++ 3 string Assignment and Concatenation Assignment s2 = s1; Makes a separate copy s2.assign(s1); Same as s2 = s1; mystring.assign(s, start, N); Copies N characters from s, beginning at index start Several overloaded versions of assign() See Individual characters s2[0] = s3[2]; s2.at(0) = s3.at(2); // performs range check Lec 10 Programming in C++ 4 2
3 string Assignment and Concatenation Range checking s3.at( index ); Returns character at index Can throw out_of_range exception [] has no range checking Concatenation s3.append( "pet" ); s3 += "pet"; Both add "pet" to end of s3 s3.append( s1, start, N ); Appends N characters from s1, beginning at index start Other overloaded versions of append exist Lec 10 Programming in C++ 5 Comparing strings Overloaded operators ==,!=, <, >, <= and >= Return bool s1.compare(s2) Returns positive if s1 lexicographically greater Compares letter by letter 'B' lexicographically greater than 'A' Returns negative if less, zero if equal s1.compare(start, length, s2, start, length) Compare portions of s1 and s2 s1.compare(start, length, s2) Compare portion of s1 with all of s2 Lec 10 Programming in C++ 6 3
4 Substrings and Swapping strings Function substr gets substring s1.substr( start, N ); Gets N characters, beginning with index start Returns substring string str= "We think in generalities, but we live in details."; string str2; str2 = str.substr (12,12); // "generalities" s1.swap(s2); Switch contents of two strings Lec 10 Programming in C++ 7 Member functions string Characteristics s1.size() and s1.length() Number of characters in string s1.capacity() Number of elements that can be stored without reallocation s1.max_size() Maximum possible string size If exceeded, a length_error exception is thrown s1.empty() Returns true if empty s1.resize(newlength) Resizes string to newlength Lec 10 Programming in C++ 8 4
5 Finding Strings and Characters in a string Find functions If found, index returned If not found, string::npos returned Public static constant in class string s1.find( s2 ) s1.find( s2, pos ) s1.rfind( s2 ) Searches right-to-left s1.find_first_of( s2 ) Returns first occurrence of any character in s2 s1.find_first_of( "abcd" ) Returns index of first 'a', 'b', 'c' or 'd' Lec 10 Programming in C++ 9 Finding Strings and Characters in a string Find functions s1.find_last_of( s2 ) Finds last occurrence of any character in s2 s1.find_first_not_of( s2 ) Finds first character NOT in s2 s1.find_last_not_of( s2 ) Finds last character NOT in s2 Lec 10 Programming in C
6 Replacing Characters in a string s1.erase( start ) Erase from index start to end of string, including start Replace s1.replace( begin, N, s2) begin: index in s1 to start replacing N: number of characters to replace s2: replacement string s1.replace( begin, N, s2, index, num ) index: element in s2 where replacement begins num: number of elements to use when replacing Replacement can overwrite characters Lec 10 Programming in C++ 11 An Example int position = string1.find(. ); //replace all periods with two semicolons //Note: this will overwrite characters while ( position!= string::npos ) { string1.replace(position, 2, xxxxx;;yyy, 5, 2); position = string1.find(., position+1); Lec 10 Programming in C
7 Inserting Characters into a string s1.insert( index, s2 ) Inserts s2 at index It does not overwrite other characters s1.insert( index, s2, index2, N ); Inserts substring of s2 at position index Substring is N characters, starting at index2 Example: String s1( beginning end ); String s2 ( middle ); S1.insert(10, s2); cout << s1; // beginning middle end Lec 10 Programming in C++ 13 Conversion to C-Style char * Strings Conversion functions strings not necessarily null-terminated s1.copy( ptr, N, index ) Copies N characters into the array ptr Starts at location index of s1 Add explicitly null as last character s1.c_str() Returns const char * Null terminated s1.data() Returns const char * NOT null-terminated Lec 10 Programming in C
8 Iterators Iterators Forwards and backwards traversal of strings Access to individual characters Similar to pointer operations Example string s1( Testing iterators!! ); const_iterator iterator = s1.begin(); while ( iterator!= s1.end() ) { cout << *iterator; ++iterator; Lec 10 Programming in C++ 15 string Stream Processing I/O of strings to and from memory Called in-memory I/O or string stream processing #include <sstream> and <iostream> headers String input class istringstream (input from string) istringstream s( ); int i, j; s >> i >> j; Like reading from cin. Can be used for data validation 1. Read a line to a string 2. Check the contents and repair, if needed 3. Input from the string Lec 10 Programming in C
9 String output class String Stream Processing ostringstream (output to a string) ostringstream s; s << "A number: " << setprecision(5) << sqrt(2) << endl; s << "Scientific notation: " << setw(20) << scientific << sqrt(2); cout << s.str() << endl; Take advantage of the formatting capabilities of C++ streams. Lec 10 Programming in C++ 17 Exceptions and Exception Handling Exceptions Indicates problem occurred in program Exception Handling Resolve exceptions Program may be able to continue Controlled termination Write fault-tolerant programs A divide-by-zero error Unsuccessful memory allocation Arithmetic overflow Invalid function parameters Out-of-range array subscripts Lec 10 Programming in C
10 Exception-Handling Terminology Terminology Function that has error throws an exception Exception handler (if it exists) can deal with problem Catches and handles exception If no exception handler, uncaught exception Program terminates Lec 10 Programming in C++ 19 C++ code Exception-Handling Overview try { code that may raise exception catch (exceptiontype1){ code to handle exception 1 try block encloses code that may raise exception One or more catch blocks follow Catch and handle exception, if appropriate Take parameter, to access exception object Lec 10 Programming in C
11 try { v = f(pi, i); Exception may occur in this block v *= v; catch (overflow_error &Error){ cout << Error.what() << endl; cout << v << endl; int f(double d, int i){ if ((i > 20) (d > MAX_VALUE)) throw overflow_error(); d = power(d,10); return ceil(d*fact(i)); Function terminates Local variables are destroyed Search for enclosing catch block Lec 10 Programming in C++ 21 Exception-Handling Overview Throw point Location in try block where exception occurred If exception handled Program skips remainder of try block Resumes after catch blocks If not handled Function terminates Looks for enclosing catch block If no exception Program skips catch blocks Lec 10 Programming in C
12 Exception-Handling Example: Divide by Zero Keyword throw Throws an exception Use when error occurs Can throw almost anything (exception object, integer, etc.) throw myobject; throw 5; Exception objects Base class exception ( <exception> ) Constructor can take a string (to describe exception) Member function what() returns that string Lec 10 Programming in C // Fig. 13.1: fig13_01.cpp 2 // A simple exception-handling example that checks for 3 // divide-by-zero exceptions. 4 #include <iostream> 5 6 using std::cout; 7 using std::cin; 8 using std::endl; 9 10 #include <exception> Define new exception class using std::exception; (inherit from exception). Pass a descriptive message to 13 the constructor. 14 // DivideByZeroException objects should be thrown by functions 15 // upon detecting division-by-zero exceptions 16 class DivideByZeroException : public exception { public: // constructor specifies default error message 21 DivideByZeroException::DivideByZeroException() 22 : exception( Attempted to divide by zero!" ) { ; // end class DivideByZeroException 25 Lec 10 Programming in C
13 26 // perform division and throw DivideByZeroException object if 27 // divide-by-zero exception occurs 28 double quotient( int numerator, int denominator ) 29 { 30 // throw DivideByZeroException if trying to divide by zero 31 if ( denominator == 0 ) 32 throw DivideByZeroException(); // terminate function // return division result 35 return (double( numerator )) / denominator; 36 If the denominator is zero, throw 37 // end function quotient a DivideByZeroException int main() object. 40 { 41 int number1; // user-specified numerator 42 int number2; // user-specified denominator 43 double result; // result of division cout << "Enter two integers (end-of-file to end): "; 46 Lec 10 Programming in C // enable user to enter two integers to divide 48 while ( cin >> number1 >> number2 ) { // try block contains code that might throw exception 51 // and code that should not execute if an exception occurs 52 try { 53 result = quotient( number1, number2 ); 54 cout << "The quotient is: " << result << endl; // end try // exception handler handles a divide-by-zero exception 59 catch ( DivideByZeroException ÷byzeroexception ) { 60 cout << "Exception occurred: " 61 << dividebyzeroexception.what() << endl; // end catch cout << "\nenter two integers (end-of-file to end): "; // end while cout << endl; return 0; // terminate normally // end main Lec 10 Programming in C
14 Exception Specifications List of exceptions function can throw Also called throw list int somefunction( double value ) throw ( ExceptionA, ExceptionB, ExceptionC ) { // function body Can only throw ExceptionA, ExceptionB, and ExceptionC (and derived classes) If throws other type, function unexpected called By default, terminates program If no throw list, can throw any exception If empty throw list, cannot throw any exceptions Lec 10 Programming in C++ 27 Stack Unwinding If exception thrown but not caught Goes to enclosing try block Terminates current function Unwinds function call stack Looks for try/catch that can handle exception If none found, unwinds again If exception never caught Calls terminate Lec 10 Programming in C
15 int main() { try { func1(5); catch (runtime_error &error) { cout << error.what() << endl; main() return 0; func1 terminates func1(5) func2 terminates func2(5) Local variables are destroyed Space freed Destructors called func3 terminates func3(5) No try/catch that can handle the exception throw runtime_error( Error!!! ); Lec 10 Programming in C++ 29 Constructors and Exception Handling Error in constructor Example: new fails; cannot allocate memory How to inform user? Constructor cannot return a value to indicate an error Hope user examines object, notices improperly constructed object Set some global variable Good alternative: throw an exception Destructors automatically called for member objects Called for automatic variables in try block Lec 10 Programming in C
16 Destructors and Exception Handling MyObject *objptr = new MyObject[10]; try { delete [] objptr; // calls the destructor catch ( ){ code to handle exception To catch all exceptions Lec 10 Programming in C++ 31 Exceptions and Inheritance Exception classes Can be derived from base classes i.e., exception If catch can handle base class, can handle derived classes Polymorphic programming try { code that may raise exception catch (exception &error){ Can catch a reference code to handle exception to all objects of a derived class of exception Lec 10 Programming in C
17 Standard Library Exception Hierarchy Exception hierarchy Base class exception (<exception>) Virtual function what, overridden to provide error messages Sample derived classes runtime_error, logic_error bad_alloc, bad_cast Thrown by new, dynamic_cast To catch all exceptions catch(...) catch(exception &AnyException) Will not catch all possible exceptions Lec 10 Programming in C++ 33 Processing new Failures When new fails to get memory 1. Should throw bad_alloc exception Defined in <new> Compliant with C++ standard 2. Some compilers have new return 0 onn failure Not compliant with C++ standard 3. A new-handler function can be registered by the user with set_new_handler It defers the error handling to the new-handler function Lec 10 Programming in C
18 1 // Fig. 13.4: fig13_04.cpp 2 // Demonstrating pre-standard new returning 0 when memory 3 // is not allocated. 4 #include <iostream> 5 6 using std::cout; 7 8 int main() 9 { 10 double *ptr[ 50 ]; // allocate memory for ptr 13 for ( int i = 0; i < 50; i++ ) { Demonstrating new that 14 ptr[ i ] = new double[ ]; returns 0 on allocation 15 failure. 16 // new returns 0 on failure to allocate memory 17 if ( ptr[ i ] == 0 ) { 18 cout << "Memory allocation failed for ptr[ " 19 << i << " ]\n"; break; // end if 24 Lec 10 Programming in C // Fig. 13.5: fig13_05.cpp 2 // Demonstrating standard new throwing bad_alloc when memory 3 // cannot be allocated. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 #include <new> // standard operator new using std::bad_alloc; int main() 14 { 15 double *ptr[ 50 ]; // attempt to allocate memory 18 try { 19 Demonstrating new that 20 // allocate memory for ptr[ i ]; 21 // new throws bad_alloc on failure throws an exception. 22 for ( int i = 0; i < 50; i++ ) { 23 ptr[ i ] = new double[ ]; 24 cout << "Allocated doubles in ptr[ " 25 << i << " ]\n"; // end try Lec 10 Programming in C
19 29 30 // handle bad_alloc exception 31 catch ( bad_alloc &memoryallocationexception ) { 32 cout << "Exception occurred: " 33 << memoryallocationexception.what() << endl; // end catch return 0; // end main Lec 10 Programming in C++ 37 Processing new Failures set_new_handler Header <new> Register function to call when new fails Takes function pointer to function that Takes no arguments Returns void Once registered, function called instead of throwing exception Lec 10 Programming in C
20 1 // Fig. 13.6: fig13_06.cpp 2 // Demonstrating set_new_handler. 3 #include <iostream> 4 5 using std::cout; 6 using std::cerr; 7 8 #include <new> // standard operator new and set_new_handler 9 10 using std::set_new_handler; #include <cstdlib> // abort function prototype The custom handler must take no arguments and return void customnewhandler() void. 15 { 16 cerr << "customnewhandler was called"; 17 abort(); // using set_new_handler to handle failed memory allocation 21 int main() 22 { 23 double *ptr[ 50 ]; 24 Lec 10 Programming in C // specify that customnewhandler should be called on failed 26 // memory allocation 27 set_new_handler( customnewhandler ); // allocate memory for ptr[ i ]; customnewhandler will be 30 // called on failed memory allocation 31 for ( int i = 0; i < 50; i++ ) { 32 ptr[ i ] = new double[ ]; cout << "Allocated doubles in ptr[ " 35 << i << " ]\n"; Note call to // end for set_new_handler return 0; // end main Lec 10 Programming in C
21 Class auto_ptr and Dynamic Memory Allocation Declare pointer, allocate memory with new What if exception occurs before you can delete it? Memory leak!!! Template class auto_ptr can help us Lec 10 Programming in C++ 41 Class auto_ptr Template class auto_ptr #include <memory> Like regular pointers (has * and ->) When pointer goes out of scope, calls delete Prevents memory leaks Usage auto_ptr< MyClass > newpointer( new MyClass() ); newpointer points to dynamically allocated object Lec 10 Programming in C
22 1 // Fig. 13.7: fig13_07.cpp 2 // Demonstrating auto_ptr. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <memory> 9 10 using std::auto_ptr; // auto_ptr class definition class Integer { public: // Integer constructor 17 Integer( int i = 0 ) 18 : value( i ) 19 { 20 cout << "Constructor for Integer " << value << endl; // end Integer constructor 23 Lec 10 Programming in C // Integer destructor 25 ~Integer() 26 { 27 cout << "Destructor for Integer " << value << endl; // end Integer destructor // function to set Integer 32 void setinteger( int i ) 33 { 34 value = i; // end function setinteger // function to return Integer 39 int getinteger() const 40 { 41 return value; // end function getinteger private: 46 int value; ; // end class Integer 49 Lec 10 Programming in C
23 50 // use auto_ptr to manipulate Integer object 51 int main() 52 { 53 cout << "Creating an auto_ptr object that points to an " 54 << "Integer\n"; Object created dynamically. // "aim" auto_ptr at Integer object 57 Integer* ptrtointeger = new Integer( 7 ); cout << "\nusing the auto_ptr to manipulate the Integer\n"; // use auto_ptr to set Integer value 62 ptrtointeger->setinteger( 99 ); // use auto_ptr to get Integer value 65 cout << "Integer after setinteger: " 66 << ( *ptrtointeger ).getinteger() If an exception 67 << "\n\nterminating program" << endl; occurs local 68 variables, e.g. delete ptrtointeger; ptrtointeger, are 69 return 0; destroyed but memory // end main is not deallocated. Lec 10 Programming in C // use auto_ptr to manipulate Integer object 51 int main() 52 { 53 cout << "Creating an auto_ptr object that points to an " 54 << "Integer\n"; // "aim" auto_ptr at Integer object 57 auto_ptr< Integer > ptrtointeger( new Integer( 7 ) ); cout << "\nusing the auto_ptr to manipulate the Integer\n"; // use auto_ptr to set Integer value 62 ptrtointeger->setinteger( 99 ); // use auto_ptr to get Integer value 65 cout << "Integer after setinteger: " 66 << ( *ptrtointeger ).getinteger() 67 << "\n\nterminating program" << endl; return 0; // end main Create an auto_ptr. It can be manipulated like a regular pointer. delete not explicitly called, but the auto_ptr will be destroyed once it leaves scope. Thus, the destructor for class Integer will be called. Lec 10 Programming in C
IS 0020 Program Design and Software Tools
1 Introduction 2 IS 0020 Program Design and Software Tools Exception Handling Lecture 12 November 23, 200 Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually
More informationLecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)
Lecture 10 Class string Namespaces Preprocessor directives Macros Conditional compilation Command line arguments Character handling library void* TNCG18(C++): Lec 10 1 Class string Template class
More informationException Handling Pearson Education, Inc. All rights reserved.
1 16 Exception Handling 2 I never forget a face, but in your case I ll make an exception. Groucho Marx It is common sense to take a method and try it. If it fails, admit it frankly and try another. But
More information! Errors can be dealt with at place error occurs
UCLA Stat 1D Statistical Computing and Visualization in C++ Instructor: Ivo Dinov, Asst. Prof. in Statistics / Neurology University of California, Los Angeles, Winter 200 http://www.stat.ucla.edu/~dinov/courses_students.html
More informationException Handling in C++
Exception Handling in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by
More informationException Handling Pearson Education, Inc. All rights reserved.
1 16 Exception Handling 2 16.1 Introduction Exceptions Indicate problems that occur during a program s execution Occur infrequently Exception handling Can resolve exceptions Allow a program to continue
More informationClass string and String Stream Processing Pearson Education, Inc. All rights reserved.
1 18 Class string and String Stream Processing 2 18.1 Introduction C++ class template basic_string Provides typical string-manipulation operations Defined in namespace std typedefs For char typedef basic_string
More informationCSC 330 Object-Oriented Programming. Exception Handling CSC 330
Object-Oriented Programming Exception Handling 1 C++ Exception Handling Topics Exception Handling C++ Exception Handling Basics Throwing and Catching Exceptions Constructors, Destructors and Exceptions
More informationIntroduction. Common examples of exceptions
Exception Handling Introduction Common examples of exceptions Failure of new to obtain memory Out-of-bounds array subscript Division by zero Invalid function parameters Programs with exception handling
More informationC++ Exception Handling 1
C++ Exception Handling 1 An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More information21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;
- 147 - Advanced Concepts: 21. Exceptions Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers.
More informationAssertions and Exceptions
CS 247: Software Engineering Principles Assertions and Exceptions Reading: Eckel, Vol. 2 Ch. 1 Exception Handling U Waterloo CS247 (Spring 2017) p.1/32 Defensive Programming The question isn t whether
More informationPIC10B/1 Winter 2014 Exam I Study Guide
PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand
More informationObject-Oriented Principles and Practice / C++
Object-Oriented Principles and Practice / C++ Alice E. Fischer June 8, 2015 OOPP / C++ Lecture 7... 1/20 Program Errors Error Handling Techniques Exceptions in C++ Exception Definition Syntax Throwing
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationUnit 4 Basic Collections
Unit 4 Basic Collections General Concepts Templates Exceptions Iterators Collection (or Container) Classes Vectors (or Arrays) Sets Lists Maps or Tables C++ Standard Template Library (STL Overview A program
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationC++ Crash Kurs. Exceptions. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck
C++ Crash Kurs Exceptions Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ Exceptions: Introduction What are exceptions Exceptions are
More informationOperator Overloading in C++ Systems Programming
Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationwhat are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8
today: strings what are strings what are strings and why to use them reading: textbook chapter 8 a string in C++ is one of a special kind of data type called a class we will talk more about classes in
More informationCS102 C++ Exception Handling & Namespaces
CS102 C++ Exception Handling & Namespaces Bill Cheng http://merlot.usc.edu/cs102-s12 1 Topics to cover C Structs (Ch 10) C++ Classes (Ch 11) Constructors Destructors Member functions Exception Handling
More informationC++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.
C++ TEMPLATES http://www.tutorialspoint.com/cplusplus/cpp_templates.htm Copyright tutorialspoint.com Templates are the foundation of generic programming, which involves writing code in a way that is independent
More informationby Pearson Education, Inc. All Rights Reserved. 2
Data that is formatted and written to a sequential file as shown in Section 17.4 cannot be modified without the risk of destroying other data in the file. For example, if the name White needs to be changed
More information05-01 Discussion Notes
05-01 Discussion Notes PIC 10B Spring 2018 1 Exceptions 1.1 Introduction Exceptions are used to signify that a function is being used incorrectly. Once an exception is thrown, it is up to the programmer
More informationCS11 Advanced C++ Fall Lecture 3
CS11 Advanced C++ Fall 2006-2007 Lecture 3 Today s Topics C++ Standard Exceptions Exception Cleanup Fun with Exceptions Exception Specifications C++ Exceptions Exceptions are nice for reporting many errors
More informationIntroduction to C++ Introduction to C++ 1
1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 22 November 28, 2016 CPSC 427, Lecture 22 1/43 Exceptions (continued) Code Reuse Linear Containers Ordered Containers Multiple Inheritance
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationG52CPP C++ Programming Lecture 14. Dr Jason Atkin
G52CPP C++ Programming Lecture 14 Dr Jason Atkin 1 Last Lecture Automatically created methods: A default constructor so that objects can be created without defining a constructor A copy constructor used
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Exception Handling, File Processing Lecture 11 March 30, 2004 Introduction 2 Exceptions Indicates problem occurred in program Not common An "exception" to a
More informationOutline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.
Outline Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. 1 Arrays I Array One type of data structures. Consecutive group of memory locations
More information1 Introduction to C++ C++ basics, simple IO, and error handling
1 Introduction to C++ C++ basics, simple IO, and error handling 1 Preview on the origins of C++ "Hello, World!" programs namespaces to avoid collisions basic textual IO: reading and printing values exception
More informationPointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.
Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference
More informationComputer Programming
Computer Programming Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering Session : C++ Standard Library The string Class Dr. Deepak B. Phatak & Dr. Supratik Chakraborty,
More informationJayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT
CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions
More informationstd::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin
std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin Permission is granted to copy and distribute freely, for any purpose, provided the copyright notice above is
More informationCOMP6771 Advanced C++ Programming
1.... COMP6771 Advanced C++ Programming Week 5 Part One: Exception Handling 2016 www.cse.unsw.edu.au/ cs6771 2.... Memory Management & Exception Handling.1 Part I: Exception Handling Exception objects
More informationPHY4321 Summary Notes
PHY4321 Summary Notes The next few pages contain some helpful notes that summarize some of the more useful material from the lecture notes. Be aware, though, that this is not a complete set and doesn t
More informationvoid fun() C::C() // ctor try try try : member( ) catch (const E& e) { catch (const E& e) { catch (const E& e) {
TDDD38 APiC++ Exception Handling 134 Exception handling provides a way to transfer control and information from a point in the execution to an exception handler a handler can be invoked by a throw expression
More informationJAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)
Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202
More informationDiscussion 1E. Jie(Jay) Wang Week 10 Dec.2
Discussion 1E Jie(Jay) Wang Week 10 Dec.2 Outline Dynamic memory allocation Class Final Review Dynamic Allocation of Memory Recall int len = 100; double arr[len]; // error! What if I need to compute the
More informationCS201 Latest Solved MCQs
Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability
More informationAssoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception
More informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching
More informationIntroduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts
Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More information! An exception is a condition that occurs at execution time and makes normal continuation of the program impossible.
Exceptions! Exceptions are used to signal error or unexpected events that occur while a program is running.! An exception is a condition that occurs at execution time and makes normal continuation of the
More informationQuiz Start Time: 09:34 PM Time Left 82 sec(s)
Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability
More informationCS201 Some Important Definitions
CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data
More informationWorking with Strings. Lecture 2. Hartmut Kaiser. hkaiser/spring_2015/csc1254.html
Working with Strings Lecture 2 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/spring_2015/csc1254.html Abstract This lecture will look at strings. What are strings? How can we input/output
More informationC++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15
C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of dynamic memory allocation of variables and objects in a C++ program.
More informationA Whirlwind Tour of C++
Robert P. Goddard Applied Physics Laboratory University of Washington Part 1: 3 November 2000: Object Model Part 2: 17 November 2000: Templates Part 3: 15 December 2000: STL Part 4: 30 March 2001 Exceptions
More information4 Strings and Streams. Testing.
Strings and Streams. Testing. 21 4 Strings and Streams. Testing. Objective: to practice using the standard library string and stream classes. Read: Book: strings, streams, function templates, exceptions.
More informationAN OVERVIEW OF C++ 1
AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function
More informationChapter 18 - C++ Operator Overloading
Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend
More informationCS 162, Lecture 25: Exam II Review. 30 May 2018
CS 162, Lecture 25: Exam II Review 30 May 2018 True or False Pointers to a base class may be assigned the address of a derived class object. In C++ polymorphism is very difficult to achieve unless you
More informationCourse "Data Processing" Name: Master-1: Nuclear Energy Session /2018 Examen - Part A Page 1
Examen - Part A Page 1 1. mydir directory contains three files: filea.txt fileb.txt filec.txt. How many files will be in the directory after performing the following operations: $ ls filea.txt fileb.txt
More informationCOMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions
COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions Dan Pomerantz School of Computer Science 19 March 2012 Overloading operators in classes It is useful sometimes to define
More informationG52CPP C++ Programming Lecture 16
G52CPP C++ Programming Lecture 16 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Casting static cast dynamic cast const cast reinterpret cast Implicit type conversion 2 How
More informationSoftware Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example
Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell
More informationDiscussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage:
Discussion 1H Notes (Week 4, April 22) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 Passing Arguments By Value and By Reference So far, we have been passing in
More informationArrays. Week 4. Assylbek Jumagaliyev
Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationCpt S 122 Data Structures. Course Review Midterm Exam # 2
Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm
More informationPreface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.
Preface to the Second Edition p. iii Preface to the First Edition p. vi Brief Contents p. ix Introduction to C++ p. 1 A Review of Structures p. 1 The Need for Structures p. 1 Creating a New Data Type Using
More informationCS242 COMPUTER PROGRAMMING
CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing
More informationCS11 Advanced C++ Lecture 2 Fall
CS11 Advanced C++ Lecture 2 Fall 2006-2007 Today s Topics C++ strings Access Searching Manipulation Converting back to C-style strings C++ streams Error handling Reading unformatted character data Simple
More informationCS201- Introduction to Programming Current Quizzes
CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements
More informationType Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works
Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.
More informationInternationalization and Error Handling
CS193D Handout 22 Winter 2005/2006 March 6, 2006 Internationalization and Error Handling See also: Chapter 14 (397-400) and Chapter 15 Internationalization and Error Handling CS193D, 3/6/06 1 Characters
More informationCSE 333 Lecture 9 - intro to C++
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia & Agenda Main topic: Intro to C++ But first: Some hints on HW2 Labs: The
More informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationCSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia New exercise posted yesterday afternoon, due Monday morning - Read a directory
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005 Introduction 2 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical
More informationObjectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program
Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationChapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationChapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction
Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers
More information1 of 8 3/28/2010 8:03 AM C++ Special Topics Home Class Info Links Lectures Newsgroup Assignmen This is a short review of special topics in C++ especially helpful for various assignments. These notes are
More informationChapter 1 Introduction to Computers and C++ Programming
Chapter 1 Introduction to Computers and C++ Programming 1 Outline 1.1 Introduction 1.2 What is a Computer? 1.3 Computer Organization 1.7 History of C and C++ 1.14 Basics of a Typical C++ Environment 1.20
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Error Handling and Exceptions Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer
More informationChapter 3 - Functions
Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number
More information17.1 Handling Errors in a Program
Chapter 17: Exceptions From the board game MONOPOLY, the rule to follow when your man lands on the illegal square: Go to jail. Go directly to jail, do not pass GO and do not collect $200. 17.1 Handling
More informationMidterm Review. PIC 10B Spring 2018
Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 19 November 7, 2018 CPSC 427, Lecture 19, November 7, 2018 1/18 Exceptions Thowing an Exception Catching an Exception CPSC 427, Lecture
More informationExceptions, Templates, and the STL
Exceptions, Templates, and the STL CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 16 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/
More informationTemplates and Vectors
Templates and Vectors 1 Generic Programming function templates class templates 2 the STL vector class a vector of strings enumerating elements with an iterator inserting and erasing 3 Writing our own vector
More informationCh. 10, The C++ string Class
Ch. 10, The C++ string Class 1 Constructing a String You can create an empty string using string s no-arg constructor like this one: string newstring; You can create a string object from a string value
More informationCHAPTER 3 Expressions, Functions, Output
CHAPTER 3 Expressions, Functions, Output More Data Types: Integral Number Types short, long, int (all represent integer values with no fractional part). Computer Representation of integer numbers - Number
More informationPointers. Developed By Ms. K.M.Sanghavi
Pointers Developed By Ms. K.M.Sanghavi Memory Management : Dynamic Pointers Linked List Example Smart Pointers Auto Pointer Unique Pointer Shared Pointer Weak Pointer Memory Management In order to create
More informationcalling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!
Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns
More informationMore on Templates. Shahram Rahatlou. Corso di Programmazione++
More on Templates Standard Template Library Shahram Rahatlou http://www.roma1.infn.it/people/rahatlou/programmazione++/ it/ / h tl / i / Corso di Programmazione++ Roma, 19 May 2008 More on Template Inheritance
More informationProgramming in C++: Assignment Week 8
Programming in C++: Assignment Week 8 Total Marks : 20 September 9, 2017 Question 1 Consider the following code segment. Mark 2 void myfunction(int test) { try { if (test) throw test; else throw "Value
More informationThrowing exceptions 02/12/2018. Throwing objects. Exceptions
ECE 150 Fundamentals of Programming Outline 2 In this lesson, we will: See that we can throw objects Know that there are classes defined in the standard template library These classes allow more information
More informationLecture Topics. Administrivia
ECE498SL Lec. Notes L8PA Lecture Topics overloading pitfalls of overloading & conversions matching an overloaded call miscellany new & delete variable declarations extensibility: philosophy vs. reality
More informationI BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.
Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Reaccredited at the 'A' Grade Level by the NAAC and ISO 9001:2008 Certified CRISL rated 'A'
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 10 October 1, 2018 CPSC 427, Lecture 10, October 1, 2018 1/20 Brackets Example (continued from lecture 8) Stack class Brackets class Main
More informationC++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay
C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming
More informationMore C++ Classes. Systems Programming
More C++ Classes Systems Programming C++ Classes Preprocessor Wrapper Time Class Case Study Class Scope and Assessing Class Members Using handles to access class members Access and Utility Functions Destructors
More information