Object Oriented Programming Elhanan Borenstein Lecture #12 copyrights © Elhanan Borenstein.

Slides:



Advertisements
Similar presentations
Copyright © 2003 Pearson Education, Inc. Slide 1.
Advertisements

1.00 Lecture 37 A Brief Look at C++: A Guide to Reading C++ Programs.
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Introduction to Linked Lists In your previous programming course, you saw how data is organized and processed sequentially using an array. You probably.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
1 CSC241: Object Oriented Programming Lecture No 28.
DYNAMIC MEMORY MANAGEMENT. int x; When the source code containing this statement is compiled and linked, an executable file is generated. When the executable.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
. Plab – Tirgul 10 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
1 Data Structures Data Structures Topic #2. 2 Today’s Agenda Data Abstraction –Given what we talked about last time, we need to step through an example.
Data Structures Topic #3. Today’s Agenda Ordered List ADTs –What are they –Discuss two different interpretations of an “ordered list” –Are manipulated.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
C++ Interlude 2 Pointers, Polymorphism, and Memory Allocation
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 16 Exceptions,
Chapter 3: Arrays, Linked Lists, and Recursion
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Object Oriented Programming Elhanan Borenstein Lecture #6.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
Review C++ exception handling mechanism Try-throw-catch block How does it work What is exception specification? What if a exception is not caught?
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Data Structures Using C++ 2E
Object Oriented Programming Elhanan Borenstein Lecture #4.
Object Oriented Programming Elhanan Borenstein Lecture #11 copyrights © Elhanan Borenstein.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Object Oriented Programming Elhanan Borenstein copyrights © Elhanan Borenstein.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Software Design 1.1 Tapestry classes -> STL l What’s the difference between tvector and vector  Safety and the kitchen sink What happens with t[21] on.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
Object Oriented Programming Elhanan Borenstein Lecture #10 copyrights © Elhanan Borenstein.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Object Oriented Programming Elhanan Borenstein Lecture #5.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Copyright © 2009 – Curt Hill Standard Template Library An Introduction.
Object Oriented Programming Elhanan Borenstein Lecture #7.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
Data Structures and Algorithm Analysis Dr. Ken Cosh Linked Lists.
LINKED LISTS.
Exception handling.
Introduction to Computers Computer Generations
Object-Oriented Programming (OOP) Lecture No. 45
Exceptions, Templates, and the Standard Template Library (STL)
Standard Version of Starting Out with C++, 4th Edition
Exceptions, Templates, and the Standard Template Library (STL)
Objects Managing a Resource
Standard Template Library
Standard Template Library
Exceptions.
Presentation transcript:

Object Oriented Programming Elhanan Borenstein Lecture #12 copyrights © Elhanan Borenstein

Agenda STL – A Brief Overview Exception Handling Exceptions and Polymorphism Reference Counting copyrights © Elhanan Borenstein

STL Brief Overview & Examples copyrights © Elhanan Borenstein

STL copyrights © Elhanan Borenstein The classes, and algorithms we saw in the previous slides are actually a simulation of the way STL classes, containers and algorithms work. … and now for a brief overview of what STL really includes. In general STL includes the following components:  Data Structures – (vector, list, set, …)  Generic Algorithms – (for each, find, sort, …)  Object Functions  Allocators Introduction

STL copyrights © Elhanan Borenstein STL provides the following data structures:  vector – dynamic array (supporting resizing)  deque – a queue or a stack  list – doubly linked list  map – Hashtable (key, value pairs)  multimap – Hashtable, supports numerous values for each key  set – Hashtable, storing keys only. Each key can only be stored once  multiset – Hashtable, storing keys only (may be stored several times) All DS supports: begin(), end(), insert(…), erase(…), clear(...) Data Structures

STL copyrights © Elhanan Borenstein All algorithms appear in the header file Include: for_each (analog to our Apply()), find, find_if, count, replace, copy, sort, reverse and many more. Generic Algorithms Commonly used with STL. Include: pow, sqrt, sin, other math functions, complex numbers functions, logic functions, comparison functions and many more. Object Functions

STL - Examples copyrights © Elhanan Borenstein Example : STL1.cpp Example : STL2.cpp (merging a vector and a list) Names: {She Sells Sea Shealls by the Sea Shore } Number of names starts with S = 6 Numbers Vector { } Numbers List { } Numbers Deque (merged) { }

Exception Handling

Exceptions As there may be certain actions which can cause run-time problems, we need some sort of mechanism to report and handle these potential errors. We can use the return-value mechanism. This mechanism have several problems:  We may forget to check the return value.  There may not be an available value we can use. Example!!!  We have to check the return value for each and every function separately. The solution: Exceptions!!!  The function does not use the return value but rather throws an exception.  The calling code will include a special block to handle exceptions. Motivation

Exceptions Exception handling is implemented with 3 keywords:  throw … – when an error occurred in a function it will use “throw” to throw a certain object (of any type).  try – the “problematic” function call, will be nested within a “try” block.  Catch (…) – one or more catch blocks should immediately follow the try block. if the function throws an exception, this block will handle it. Every catch block can handle only one type of exception. If there may be more than one type of exception, we should implement several catch block. The most important feature of that mechanism, is that the function in which the error was detected, forces that calling function to handle it. Example: exm_exc Usage

Exceptions Any type of object can be thrown as exception. It is common to throw objects of a certain class family. If the exception is not caught, it will percolate up, (function after function) until reaching the main (where it will abort).  Conclusions: Somewhere, sometime, someone is going to pay!!! No casting takes place!!! If more than one catch block fits the exception type, the first will be used (e.g. void* will take all pointers). catch (…) can catch all types:  Can’t use the thrown object (WHY?)  Should be last!!! An exception can be throws again (using “throw” command) Exception Handling

Exceptions The exception handling mechanism was only recently added to C++ as a standard component. Old libraries and classes may not use this mechanism.  Memory Allocation – compiler dependent. Some throw an exception of type xalloc. Most simply return NULL.  Dynamic Cast – compiler dependent. Some throw an exception of type bad_cast.  File Handling – Unfortunately, C++ file handling classes does not use exceptions.  MFC – A good example for exception usage. See documentation. Haw can we solve that problem? Compatibility

Exceptions A function can declare which exception it may throw Should appear in both prototype and implementation). This mechanism limits the exceptions that the function can throw and thus ensures that if we handle the declared exceptions, we are all covered.  void f1() throw (ABC, int); can throw only objects of type ABC or int !!!  void f2() throw (int); can throw only objects of type int !!!  void f3() throw (); cannot throw any type of object !!!  void f4() can throw any type of object !!! Declaring thrown Exceptions Important: A function that throw an exception that was not declare will not be detected in compilation or linkage, but would rather crush the application when this exception is thrown.

Exceptions Naturally, exceptions are very suitable for constructors (no return value!!!) If the C’tor did not terminate properly (an exception was thrown), the d’tor will not be activated. Allocated memory should be released before throwing the exception or in the catch block. but … if the exception was thrown from the C’tor of the derived class, the D’tor of the base class will be activated. (WHY?) Example: exc_ctor.cpp A few notes!!! Throwing Exceptions in C’tors and D’tors

Exceptions & Polymorphism

Exceptions and Polymorphism As we recall, the catch block does not perform casting !!! But still…one exception may fit more than one catch block when pointers/references are involved (e.g. void* fit int*) We can use this property, combined with polymorphism:  We will implement a catch block for the base class (by ref!!!)  This block will also catch all the derived classes  Using virtual functions, we can implement a general error handling code that will work according to he actual error !!! (This mechanism is commonly used in MFC. A full hierarchy of Exception class was implemented) Introduction

Exceptions and Polymorphism Note: To use polymorphism, the catch block should receive either a pointer or a reference to the object.  using references is sufficient to support polymorphism and doesn’t require dynamic allocation. Example: exc_ploy.cpp A few Notes:  CError is the base class of all the exception class. Thus, the catch block will catch also the derived class.  Since DoManyThings() declares it throws CError, it may throw CError or any of it derived classes.  The temporary exception objects lives until the end of the catch block where it was caught. Example

Reference Counting

When ever we had a class that used dynamic allocation (e.g. String) we ran into the following two problems: The Problem: The Solution: A brief history of the dual referencing Who will free the allocated memory (when the object dies)? How to avoid dual referencing (when copying or assigning to another object)? If one object changes the content of the allocated memory it will affect all others object with the same reference If one object dies and free the allocated memory, it will leave all other with a dead reference. Implement a destructor which will free the allocated memory Implement a C.C. and assignment oper’ which will create their own copy + +

Reference Counting But…there may be a different (and more efficient) solution. Let’s allow two object to point to the same allocated memory (as a result of assignment of copy c’tor). To solve the problem of updating the memory:  An object that is about to change the content of the shared memory, will first create its own copy (“Copy on Write”). To solve the problem of freeing an allocated memory:  Only if the object that is being destructed detects that no other object is pointing to the same memory, it will free that memory. Advantages - Efficiency:  Perform a copy operation only when needed.  Use less memory. A different solution…

Reference Counting Copy on Write – Simple. When ever we want to change the content of the allocated memory, we will first allocate a new copy. Freeing Memory – We must implement a Reference Counting mechanism.  We will count the number of object pointing to the same memory.  Every time an object dies (or create its own copy) we deduce 1 from the counter.  If the counter reaches 0 – we will delete that memory. And technically – we will add to the class String, a pointer to int, which will point to a shared reference counter. So, how can we implement that concept?

Reference Counting str1str2str3str4str5str6 “John”“Sam”“John” 3 21

Reference Counting str1str2str3str4str5str6 “John” 2 21 “Bill” 1 Copying

Reference Counting str1str2str3str4str5str6 “John” 2 11 “Bill” 1 Deleting

Reference Counting str1str2str3str4str5str6 “John” 2 01 “Bill” 1 Deleting

Reference Counting str1str2str3str4str5str6 “John” 2 01 “Bill” 1 Deleting

Reference Counting Example: String.cpp And, a short example!!!

Questions? copyrights © Elhanan Borenstein