CPSC 427: Object-Oriented Programming

Similar documents
CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

Object-Oriented Principles and Practice / C++

Study Guide to Exam 2

Object-Oriented Principles and Practice / C++

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

IS 0020 Program Design and Software Tools

VALLIAMMAI ENGINEERING COLLEGE

C++ Exception Handling 1

CS11 Advanced C++ Fall Lecture 3

Short Notes of CS201

CPSC 427: Object-Oriented Programming

Cpt S 122 Data Structures. Course Review FINAL. Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University

CS201 - Introduction to Programming Glossary By

Absolute C++ Walter Savitch

COMP6771 Advanced C++ Programming

CS 162, Lecture 25: Exam II Review. 30 May 2018

CPSC 427: Object-Oriented Programming

Inheritance, and Polymorphism.

! Errors can be dealt with at place error occurs

void fun() C::C() // ctor try try try : member( ) catch (const E& e) { catch (const E& e) { catch (const E& e) {

Increases Program Structure which results in greater reliability. Polymorphism

CPSC 427: Object-Oriented Programming

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

CPSC 427a: Object-Oriented Programming

Programming, numerics and optimization

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

This examination has 11 pages. Check that you have a complete paper.

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns

Chapter 5. Object- Oriented Programming Part I

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Exceptions, Case Study-Exception handling in C++.

CPSC 427: Object-Oriented Programming

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

COEN244: Class & function templates

Polymorphism Part 1 1

CPSC 427: Object-Oriented Programming

04-24/26 Discussion Notes

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Instantiation of Template class

Object-Oriented Principles and Practice / C++

G52CPP C++ Programming Lecture 16

Homework 4. Any questions?

RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING QUESTION BANK UNIT I 2 MARKS

ECE 449 OOP and Computer Simulation Lecture 14 Final Exam Review

05-01 Discussion Notes

Programming in C++: Assignment Week 8

OBJECT ORIENTED PROGRAMMING USING C++

Exception Handling Pearson Education, Inc. All rights reserved.

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

17.1 Handling Errors in a Program

CS3157: Advanced Programming. Outline

mywbut.com Exception Handling

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Get Unique study materials from

Midterm Review. PIC 10B Spring 2018

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

TEMPLATES AND EXCEPTION HANDLING

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

Interview Questions of C++

CSCE 110 PROGRAMMING FUNDAMENTALS

7.1 Optional Parameters

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Laboratorio di Tecnologie dell'informazione

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

C++ Namespaces, Exceptions

C++_ MARKS 40 MIN

Object-Oriented Programming

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

Extending Classes (contd.) (Chapter 15) Questions:

Intermediate Programming, Spring 2017*

CS11 Introduction to C++ Fall Lecture 6

AN OVERVIEW OF C++ 1

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

Basic Array Implementation Exception Safety

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

CPSC 427a: Object-Oriented Programming

CS304 Object Oriented Programming Final Term

G52CPP C++ Programming Lecture 17

Object Oriented Programming CS250

Introduction. Common examples of exceptions

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

CPSC 427: Object-Oriented Programming

Fast Introduction to Object Oriented Programming and C++

Problem Solving with C++

CS102 C++ Exception Handling & Namespaces

Introduction to C++ Systems Programming

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Comp151. Inheritance: Initialization & Substitution Principle

Transcription:

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 Template Example CPSC 427, Lecture 22 2/43

Exceptions (continued) CPSC 427, Lecture 22 3/43

Standard exception class The standard C++ library provides a polymorphic base class std::exception from which all exceptions thrown by components of the C++ Standard library are derived. These are: exception bad alloc bad cast bad exception bad typeid ios base::failure description thrown by new on allocation failure thrown by a failed dynamic cast thrown when an exception type doesn t match any catch thrown by typeid thrown by functions in the iostream library (from http://www.cplusplus.com/doc/tutorial/exceptions/) CPSC 427, Lecture 22 4/43

Catching standard exceptions Class std::exception contains a virtual function const char* what() const; that is overridden in each derived exception class to provide a meaningful error message. Because the base class is polymorphic, it is possible to write a single catch handler that will catch all derived exception objects. Example: catch (exception& e) { cerr << "exception caught: " << e.what() << endl; } CPSC 427, Lecture 22 5/43

Deriving your own exception classes from std::exception #include <iostream> #include <exception> using namespace std; class myexception: public exception { virtual const char* what() const throw() { return "My exception happened"; } } myex; // declares class and instantiates it int main () { try { throw myex; } catch (exception& e) { cout << e.what() << endl; } return 0; } CPSC 427, Lecture 22 6/43

Multiple catch blocks Can have multiple catch blocks to catch different classes of exceptions. They are tried in order, so the more specific should come before the more general. Can have a catch-all block catch (...) that catches all exceptions. (This should be placed last.) Demo 21d-Exceptions-cards has an example of this as well. CPSC 427, Lecture 22 7/43

Rethrow A catch block can do some processing and then optionally rethrow the exception or throw a new exception. One exception can cause multiple catch blocks to execute. To rethrow the same exception, use throw; with no argument. To throw a new exception, use throw as usual with an argument. CPSC 427, Lecture 22 8/43

A subtle fact about rethrow Rethrowing the current exception is not the same as throwing an exception with the same exception object. throw e; always copies object e to special memory using the copy constructor for e s class. throw; does not make another copy of the exception object but instead uses the copy already in special memory. This difference becomes apparent if the copy is not identical to the original (possible for a custom copy constructor), or if the copy constructor has side effects (such as printing output). CPSC 427, Lecture 22 9/43

Example of rethrowing an exception (demo 22a-Exceptions-rethrow) 1 #include <iostream> 2 using namespace std; 3 class MyException { 4 public: 5 MyException() {} 6 MyException( MyException& e ) { 7 cout << "Copy constructor called\n"; } 8 ~MyException() {} 9 } myex; // declares class and instantiates it 10 int main () { 11 try { 12 try { throw myex; } 13 catch (MyException& e) { 14 cout << "Exception caught by inner catch\n"; throw; } 15 } 16 catch (MyException& err) { 17 cout << "Exception caught by outer catch\n"; 18 } 19 return 0; 20 } CPSC 427, Lecture 22 10/43

Results In the preceding example, the throw myex on line 12 causes a copy, but the throw on line 14 does not. This produces the following output: Copy constructor called Exception caught by inner catch Exception caught by outer catch CPSC 427, Lecture 22 11/43

Throw restrictions It is possible to specify that a function can only throw certain kinds of exceptions (or none at all). This feature is regarded as a bad idea because the current semantics are not what one would expect. It does not prevent the exceptions from being thrown; rather, it causes a run-time test to be inserted which calls unexpected exception() when an exception is thrown that is not listed in the function s throw specifier. CPSC 427, Lecture 22 12/43

Uncaught exceptions: Ariane 5 Uncaught exceptions have led to spectacular disasters. The European Space Agency s Ariane 5 Flight 501 was destroyed 40 seconds after takeoff (June 4, 1996). The US$1 billion prototype rocket self-destructed due to a bug in the on-board guidance software. [Wikipedia] This is not about a programming error. It is about system-engineering and design failures. The software did what it was designed to do and what it was agreed that it should do. CPSC 427, Lecture 22 13/43

Uncaught exceptions: Ariane 5 (cont.) Heres a summary of the events and its import for system engineering: A decision was made to leave a program running after launch, even though its results were not needed after launch. An overflow error happened in that calculation, An exception was thrown and, by design, was not caught. This caused the vehicle s active and backup inertial reference systems to shut down automatically. As the result of the unanticipated failure mode and a diagnostic message erroneously treated as data, the guidance system ordered violent attitude correction. The ensuing disintegration of the over-stressed vehicle triggered the pyrotechnic destruction of the launcher and its payload. CPSC 427, Lecture 22 14/43

Termination There are various conditions under which the exception-handling mechanism can fail. Two such examples are: Exception not caught by any catch block. A destructor issues a throw during the stack-unwinding process. When this happens, the function terminate() is called, which by default aborts the process. 1 This is a bad thing in production code. Conclusion: All exceptions should be caught and dealt with explicitly. 1 It s behavior can be changed by the user. CPSC 427, Lecture 22 15/43

Code Reuse CPSC 427, Lecture 22 16/43

Reusable code One of the major goals of C++ is code reusability. The desire to reuse code occurs in two very different scenarios. Sharing Different parts of a single application need the same or similar code blocks. The code should be written once and shared by the parts that need it. Mechanisms for code sharing include functions and (non-polymorphic) derivation. Libraries A code base is made available for others to use in their applications, e.g., the C++ Standard Library. Useful mechanisms include polymorphic derivation and templates. CPSC 427, Lecture 22 17/43

Problems with reusing code The problem with code reuse is that one rarely wants to reuse the exact same piece of code. Rather, one wants similar code but specialized to a particular application. For example, most useful functions take parameters which tell the function what data to compute on. Different applications can call the function with their own data. Similarly, containers such as vector make sense for many different kinds of objects. The STL container vector<t> allows the generic vector to be specialized to any suitable type T object. CPSC 427, Lecture 22 18/43

How to allow variability Code reusability becomes the problem of bridging the gap between abstract general code and specific concrete application. For functions, the various function call mechanisms bridge the gap. With polymorphic derivation, a base class pointer pointing to a specific derived class object bridges the gap. With templates, the template parameter bridges the gap. In all three cases, application-specific data must satisfy the constraints required by the general code. CPSC 427, Lecture 22 19/43

Specifying constraints One of the important mechanisms in C++ for specifying constraints is the type system. For functions, the types of the actual arguments must be compatible with the declared types of the parameters. Violations of these constraints can be detected at compile time. With polymorphic derivation, the type system also allows for some constraint checking, but a dynamic downcast (convert from pointer-to-base to pointer-to-derived) requires runtime checking. With templates, specifying and checking the constraints is more difficult. We explore some of the ways this can be done. CPSC 427, Lecture 22 20/43

Linear Containers CPSC 427, Lecture 22 21/43

Demo 19-Virtual Linked list code was introduced in demo 08-BarGraph, where a Row was a linked list of Item*, where an Item contained exam information for a particular student. Demo 19-Virtual extracted the linked list code from Row and called it Linear. The specific Item class from 08-BarGraph was renamed Exam, and the type Item was reserved for the kind of object that could be put in a linked list. CPSC 427, Lecture 22 22/43

Sharing in 19-Virtual 19-Virtual observes that stacks and queues are very similar data structures. They are both linear lists of items. Both support operations put() and pop() that allow items to be inserted into and removed from the list. The only difference is where in the list new items are inserted. The common code is in the base class Linear. The derived classes Stack and Queue override virtual base class functions as needed for their specializations. CPSC 427, Lecture 22 23/43

Abstract containers Both Stack and Queue are examples of list containers that support four operations: put, pop, peek, and print. Class Container is an abstract base class with a virtual destructor and four pure abstract functions put, pop, peek, and print. Linear is derived from Container. This ensures that any generic code for dealing with containers can handle Linear objects. However, Container is general on only one dimension. It is still specific to containers of Item* objects. CPSC 427, Lecture 22 24/43

Ordered Containers CPSC 427, Lecture 22 25/43

Demo 22b-Multiple The purpose of demo 22b-Multiple is to generalize the linear containers of demo 19-Virtual to support lists of items that are sorted according to a data-specific ordering. It does this by adding class Ordered and Item, creating two ordered containers of type class List and class PQueue, and extending the code appropriately. CPSC 427, Lecture 22 26/43

Ordered base class Ordered is an abstract class (interface) that promises items can be ordered based on an associated key. It promises functions: A function key() that returns the key associated with an item. Comparison operators < and == that compare the derived item *this with an argument key. Use: class Item : public Exam, Ordered {... }; Note: We can use private derivation because every function in Ordered is abstract and therefore must be overridden in Item. CPSC 427, Lecture 22 27/43

class Item Item is publicly derived from Exam, so it has access to Exam s public and protected members. It fulfills the promises of Ordered by defining: bool operator==(const KeyType& k) const { return key() == k; } bool operator< (const KeyType& k) const { return key() < k; } bool operator< (const Item& s) const { return key() < s.key(); } KeyType is defined with a typedef in exam.hpp to be int. CPSC 427, Lecture 22 28/43

Container base class We saw the Container abstract class in demo 19-Virtual. It promises four functions: virtual void put(item*) =0; // Put in Item virtual Item* pop() =0; // Remove Item virtual Item* peek() =0; // Look at Item virtual ostream& print(ostream&) =0; // Print all Items Use: class Linear : Container {... }; CPSC 427, Lecture 22 29/43

Additions to Linear The meaning of put(), pop(), and peek() for ordered lists is different from the unordered version, even though the interface is the same. The concept of a cursor is introduced into Linear along with new virtual functions insert() and focus() for manipulating the cursor. peek() and pop() always refer to the position of the cursor. put() inserts into the middle of the list in order to keep the list properly sorted. CPSC 427, Lecture 22 30/43

class Linear Linear implements general lists through the use of a cursor, a pair of private Cell pointers here and prior. Protected insert() inserts at the cursor. Protected focus() is virtual and must be overridden in each derived class to set the cursor appropriately for insertion. Cursors are accessed and manipulated through protected functions reset(), end(), and operator ++(). Use: List::insert(Cell* cp) {reset(); Linear::insert(cp);} inserts at the beginning of the list. CPSC 427, Lecture 22 31/43

class PQueue PQueue inserts into a sorted list. void insert( Cell* cp ) { for (reset();!end(); ++*this) { // find insertion spot. if (!(*this < cp) )break; } Linear::insert( cp ); // do the insertion. } Note the use of the comparison between a PQueue and a Cell*. This is defined in linear.hpp using the cursor: bool operator< (Cell* cp) { return (*cp->data < *here->data); } CPSC 427, Lecture 22 32/43

Multiple Inheritance CPSC 427, Lecture 22 33/43

What is multiple inheritance Multiple inheritance simply means deriving a class from two or more base classes. Recall from demo 22b-Multiple: class Item : public Exam, Ordered {... }; Here, Item is derived from both Exam and from Ordered. CPSC 427, Lecture 22 34/43

Object structure Suppose class A is multiply derived from both B and C. We write this as class A : B, C {... };. Each instance of A has embedded within it an instance of B and an instance of C. All data members of both B and C are present in the instance, even if they are not visible from within A. Derivation from each base class can be separately controlled with privacy keywords, e.g.: class A : public B, protected C {... };. CPSC 427, Lecture 22 35/43

Diamond pattern One interesting case is the diamond pattern. class D {... x... }; class B : public D {... }; class C : public D {... }; class A : public B, public C {... }; Each instance of A contains two instances of D one in B and one in C. These can be distinguished using qualified names. Suppose x is a public data member of D. le Within A, can write B::D::x to refer to the first copy, and C::D::x to refer to the second copy. CPSC 427, Lecture 22 36/43

Virtual derivation Virtual derivation allows instances of A to have only a single embedded instance of D. class D {... x... }; class B : public virtual D {... }; class C : public virtual D {... }; class A : public B, public C {... }; D s constructor is the first thing called when A is created, and it s up to A to supply any needed parameters in its ctor. CPSC 427, Lecture 22 37/43

Template Example CPSC 427, Lecture 22 38/43

Using templates with polymorphic derivation To illustrate templates, I converted 22b-Multiple to use template classes. The result is in 22c-Multiple-template. There is much to be learned from this example. Today I point out only a few features. CPSC 427, Lecture 22 39/43

Container class hierarchy As before, we have PQueue derived from Linear derived from Container. Now, each of these have become template classes with parameter class T. T is the item type; the queue stores elements of type T*. The main program creates a priority queue using PQueue<Item> P; CPSC 427, Lecture 22 40/43

Item class hierarchy As before, we have Item derived from Exam, Ordered. Item is an adaptor class. It bridges the requirements of PQueue<T> to the Exam class. CPSC 427, Lecture 22 41/43

Ordered template class Ordered<KeyType> describes an abstract interface for a total ordering on elements of abstract type KeyType. Item derives from Ordered<KeyType>, where KeyType is defined in exam.hpp using a typedef. An Ordered<KeyType> requires the following: virtual const KeyType& key() const =0; virtual bool operator < (const KeyType&) const =0; virtual bool operator == (const KeyType&) const =0; That is, there is the notion of a sort key. key() returns the key from an object satisfying the interface, and two keys can be compared using < and ==. CPSC 427, Lecture 22 42/43

Alternative Ordered interfaces As a still more abstract alternative, one could require only comparison operators on abstract elements (of type Ordered). That is, the interface would have only two promises:] virtual bool operator < (const Ordered&) const =0; virtual bool operator == (const Ordered&) const =0; This has the advantage of not requiring an explicit key, but it s also less general since keys are often used to locate elements (as is done in the demo). CPSC 427, Lecture 22 43/43