Você está na página 1de 74

1

Lecture Study Note


Good Luck ladies and gentlemen!
Contents

Data, Capta, Information & Knowledge ........................................................................ 7 Textual Information.......................................................................................................... 7 Textual Information Unstructured.............................................................................. 7 Textual Information Structured .................................................................................... 7 Textual Information Semi-Structured ........................................................................ 7 Structures ........................................................................................................................ 8 Structure Types ........................................................................................................... 8 Declare Structure Variable ........................................................................................... 8 Accessing Structure Members ..................................................................................... 8 Structure Pitfall ............................................................................................................ 9 Structures as Function Assignments ........................................................................... 9 Initializing Structures.................................................................................................... 9 Classes ........................................................................................................................... 9 Class Definitions ........................................................................................................ 10 Declaring Objects ...................................................................................................... 10 Class Member Functions ........................................................................................... 10 Class Member Functions Definition ........................................................................... 10 Dot and Scope Resolution Operator .......................................................................... 11 A Classs Place .......................................................................................................... 11 Abstract Data Types ...................................................................................................... 11 Encapsulation ............................................................................................................ 11 Principles of OOP ...................................................................................................... 12 Public and Private Members ...................................................................................... 12 Accessor and Mutator Functions ................................................................................... 12 Structures versus Classes ......................................................................................... 12

2 Summary ....................................................................................................................... 13 Software Requirements: basics ..................................................................................... 13 Objects and Object Classes .......................................................................................... 14 Modeling: class diagram ............................................................................................ 14 Modeling: use cases .................................................................................................. 14 Modeling: State Transition Diagram........................................................................... 14 Class Association and Multiplicity ................................................................................. 14 Generalization and Aggregation ................................................................................ 15 Sequence Diagram........................................................................................................ 15 Inheritance .................................................................................................................... 16 Inheritance Terminology ............................................................................................ 16 Constructors in Derived Class ....................................................................................... 16 Private Data ............................................................................................................... 16 The Protected: Qualifier ............................................................................................. 17 Redefinition of Member Functions ................................................................................. 17 Redefining verse Overloading ....................................................................................... 17 Function Signature ........................................................................................................ 17 Functions Not Inherited ................................................................................................. 18 Assignment Operators and Copy Constructors ............................................................. 18 Destructors in Derived Classes ..................................................................................... 18 Destructor Calling Order ............................................................................................ 18 Is a vs Has a Relationships ...................................................................................... 19 Protected and Private Inheritance.............................................................................. 19 Multiple Inheritances ..................................................................................................... 19 Summary ....................................................................................................................... 19 Virtual Function Basics .................................................................................................. 20 Figures Example ........................................................................................................... 20 Figures Example 2 ..................................................................................................... 20 Figures Example: center() ......................................................................................... 21 Figures Example: New Figure ................................................................................... 21 Figures Example: Virtual ............................................................................................... 21

3 Virtual Functions: Another Example........................................................................... 21 Virtual Functions: Auto Parts ..................................................................................... 22 Class Sale Definition ..................................................................................................... 22 Member Functions ..................................................................................................... 22 Class Sale ................................................................................................................. 23 Derived Class DiscountSale Defined ......................................................................... 23 DiscountSales Implementation of bill() ...................................................................... 23 Derived Class DiscountSale ...................................................................................... 24 Virtual: Wow! ................................................................................................................. 24 Virtual: How? ................................................................................................................. 24 Overriding ...................................................................................................................... 25 Virtual Functions: Why Not All? ..................................................................................... 25 Pure Virtual Functions ................................................................................................... 25 Abstract Base Classes .................................................................................................. 25 Extended Type Compatibility ......................................................................................... 26 Extended Type Compatibility Example ...................................................................... 26 Classes Pet and Dog ................................................................................................. 26 Using Classes Pet and Dog ....................................................................................... 26 Casting .......................................................................................................................... 27 Downcasting .................................................................................................................. 27 Slicing Problem ............................................................................................................. 27 Slicing Problem Example ........................................................................................... 28 Slicing Problem Example ........................................................................................... 28 Slicing Problem .......................................................................................................... 28 Virtual Destructors ......................................................................................................... 28 Inner Workings of Virtual Functions............................................................................... 28 Summary ....................................................................................................................... 29 Templates ..................................................................................................................... 29 Function Templates vs. Overloading ............................................................................. 29 Function Template Syntax............................................................................................. 30 Template Prefix ............................................................................................................. 30

4 Function Template Definition ......................................................................................... 30 Calling a Function Template .......................................................................................... 31 Another Function Template ........................................................................................... 31 showStuff Call ............................................................................................................ 31 Compiler Complications ................................................................................................ 31 More Compiler Complications ....................................................................................... 32 Algorithm Abstraction .................................................................................................... 32 Defining Templates Strategies ...................................................................................... 32 Inappropriate Types in Templates ................................................................................. 33 Class Templates ........................................................................................................... 33 Class Template Definition .......................................................................................... 33 Template Class Pair Members................................................................................... 34 Template Class Pair .................................................................................................. 34 Pair Member Function Definitions ................................................................................. 34 Class Templates as Parameters ................................................................................... 34 Class Templates Within Function Templates ................................................................ 35 Restriction on Type Parameter ...................................................................................... 35 Type Definitions ............................................................................................................ 35 Friends and Templates.................................................................................................. 35 Predefined Template Classes ....................................................................................... 36 Templates and Inheritance ............................................................................................ 36 Summary ....................................................................................................................... 36 Exception Handling Basics ............................................................................................ 36 Toy Example .............................................................................................................. 37 Toy Example try-catch ............................................................................................... 38 Try Block ....................................................................................................................... 38 Throw ............................................................................................................................ 38 Catch-Block ................................................................................................................... 38 Catch-Block Parameter .............................................................................................. 39 Defining Exception Classes........................................................................................... 39 Exception Class for Toy Example .............................................................................. 39

5 Multiple Throws and Catches ........................................................................................ 39 Catching ........................................................................................................................ 40 Throwing Exception In Function .................................................................................... 40 Exception Specification ................................................................................................. 40 Throw List...................................................................................................................... 40 Throw List Summary .................................................................................................. 41 Derived Classes ............................................................................................................ 41 Unexpected()................................................................................................................. 41 When to Throw Exceptions ........................................................................................... 41 Uncaught Exceptions .................................................................................................... 42 Rethrowing an Exception .............................................................................................. 42 Summary ....................................................................................................................... 42 Iterators ......................................................................................................................... 43 Manipulating Iterators ................................................................................................ 43 Cycling with Iterators ................................................................................................. 43 Vector Iterator Example................................................................................................. 43 Vector Iterator Types ..................................................................................................... 44 Kinds of Iterators ........................................................................................................... 45 Bidirectional and Random-Access Iterator Use ............................................................. 45 Iterator Classifications ................................................................................................... 45 Constant and Mutable Iterators ..................................................................................... 46 Reverse Iterators ........................................................................................................... 46 Reverse Iterators Correct .......................................................................................... 46 Iterator Compiler Problems ........................................................................................... 46 Containers ..................................................................................................................... 47 Sequential Containers ............................................................................................... 47 Example for Using List Template Class......................................................................... 47 Container Adapters stack and Queue ........................................................................... 48 Specifying Containers Adapters ................................................................................ 48 Associative Containers .............................................................................................. 49 Set Template Class ....................................................................................................... 49

6 More Set Template Class .......................................................................................... 49 Program Using Set Template Class........................................................................... 49 Map Template Class ..................................................................................................... 50 Program Using the Map Template ............................................................................. 51 Efficiency ....................................................................................................................... 52 Generic Algorithms ........................................................................................................ 52 Running Times .............................................................................................................. 52 Counting Operations ..................................................................................................... 53 Counting Example ..................................................................................................... 53 Big-O Notation ........................................................................................................... 53 Big-O Terminology ..................................................................................................... 54 Container Access Running Times.............................................................................. 54 Nonmodifying Sequence Algorithms .......................................................................... 55 Generic Find Function Example .................................................................................... 55 Modifying Sequence Algorithms .................................................................................... 56 Set Algorithms ........................................................................................................... 56 Sorting Algorithms ..................................................................................................... 56 Summary ....................................................................................................................... 56 Vasa Case Study Table................................................................................................. 58 Sample Questions ......................................................................................................... 59 Exception Handling Example ........................................................................................ 69 Sample Diagrams .......................................................................................................... 70 Exercise 1.2 Solutions ................................................................................................... 73 Type Checking: .......................................................................................................... 73 Style Checking: .......................................................................................................... 73 Input validation: ......................................................................................................... 74

Lecture 4
Data, Capta, Information & Knowledge
Data o Facts we may or may not focus on Capta o We focus on using cognitive settings to capture and add appreciation to the data Information o Relate the capta to other facts to be understood within a context Knowledge o Information is organized into structures which may be longer-lasting

Textual Information
Textual Information Unstructured
Refers to not have a rigid format Not being organized in discrete units Usually free text Most documents or emails are unstructured

Textual Information Structured


Organized in discrete units Similar entities are grouped together Entities in the same group have the same descriptions or attributes Descriptions for all entities in a group have the same defined format, predefined length, are all present, follow the same order

Textual Information Semi-Structured


Between structured and unstructured information Some structure exists, but there is considerable flexibility within the structure Similar entities are grouped together Entities in the same group may not have the same attributes Descriptions for all entities in a group may not have the same defined format, predefined length or follow the same order

Structures
2nd aggregate data type: struct Recall: aggregate meaning grouping o Recall array: collection of values of the same type o Structure: collection of values of different types Treated as a single time, like arrays Major difference: Must first define struct o Prior to declaring any variables

Structure Types
Define struct globally (typically) No memory is allocated o Just a placeholder for what our struct will look like Definition Struct CDAccountV1 Name of new struct type { Double balance; member names

Double interestRate; Int term; }

Declare Structure Variable


With structure type defined, now declare variables of this new type: CDAccountV1 acccount; o Just like declaring simple types o Variable account now of type CDAccountV1 o It contains member values Each of the struct parts

Accessing Structure Members


Dot Operator to access members o Account.balance o Account.interestRate o Account.term Called member variables o The parts of the structure variable

9 o Different structs can have same name member variables No conflicts

Structure Pitfall
Semicolon after structure definition ; must exist after bracket }; Required since you can declare structure variables in this location

Structures as Function Assignments


Passed like any simple data type o Pass-by-value o Pass-by-reference o Or combination Can also be returned by function o Return-type is structure type o Return statement in function definition sends structure variable back to caller

Initializing Structures
Can initialize at declaration Example: struct Date { int month; int day; int year; }; Date dueDate = {12, 31, 2003}; Declaration provides initial data to all three member variables

Classes
Similar to structures but adds member FUNCTIONS and not just member data Integral to object-oriented programming o Focus on objects

10 o Objects containing data and operations o In C++, variables of class type are objects

Class Definitions
Defined similar to structures class DayOfYear name of new class type { public: void output(); member function! int month; int day; }; Notice only member functions prototype o Functions implementation is elsewhere

Declaring Objects
Declared same as any variable with predefined type, structure type Example: DayOfYear today, birthday; //Declares two objects of class type DayOfYear Objects include: o Data Members month, day o Operations (member functions) Output()

Class Member Functions


Must define or implement class member functions Like other function definitions o Can be after main() definition o Must specify class: Void DayOfYear::output() {}

Class Member Functions Definition


Notice output() member functions definition (in next example)

11 Refers to member data of class o No qualifiers Functions used for all objects of the class will refer to that objects data when invoked

Exaple: today,output() //Displays today objects data

Dot and Scope Resolution Operator


Used to specify of what thing they are members Dot operator: o Specifies member of a particular object Scope resolution operator: o Specifies what class the function definition comes from

A Classs Place
Class is full-fledged type o Just like data types int, double, etc Can have variables of a class type o We simply call them objects Can have parameters of a class type o Pass-by-value o Pass-by-reference Can use class type like any other type

Abstract Data Types


Abstract o Programmers dont know details Abbreviated ADT o Collection of data values together with set of basic operations defined for the values ADTs often language-independent o We implement ADTs in C++ with classes C++ class defines the ADT o Other languages implement ADTs as well

Encapsulation
Means bringing together as one

12 Declare a class get an object Object is encapsulation of o Data values o Operations on the data (member functions)

Principles of OOP
Information Hiding o Details of how operations work not known to user of class Data abstraction o Details of how data is manipulated within ADT/class now known to user Encapsulation o Bring together data and operations, but keep details hidden

Public and Private Members


Data in class almost always designated private in definition o Up holds principles of OOP o Hide data from user o Allow manipulation only via operations that are member functions Public items (usually member functions) are user-accessible Can mix and match public and private Typical to place public first Outside of class definition, cannot change or access private data

Accessor and Mutator Functions


Call accessor member functions o Allow object to read data o Also called get member functions o Simple retrieval of member data Mutator member functions o Allow object to change data o Manipulated based on application User of class need not see details of how class is implemented o Principle of OOP encapsulation User only needs rules Implementation of class hidden o Member function definitions elsewhere where users cannot see them

Structures versus Classes


Structures

13 o Typically all members public o No member functions Classes o Typically all data members are private o Interface member functions public Technically, same o Perceptionally, very different mechanisms Focus for programming changes o Before algorithms center stage o OOP data is focus Algorithms still exist o They simply focus on their data o Are made to fit the data Designing software solution o Define variety of objects and how they interact

Summary
Structure is collection of different types Class used to combine data and functions into single object Class and structures types can be formal parameters to functions Member variable and member functions o Can be public accessed outside class o Can be private accessed only in member functions definition C++ class definition Should separate two key parts o Interface: what user needs o Implementation: details of how class works

Lecture 5
Software Requirements: basics
Requirements: services + constraints User requirements vs. system requirements System requirements can be:

14 o Functional requirements o Non-functional requirements o Domain requirements Non-functional requirements o Product, organization, external requirements o E.g. usability, process standard, legislative requirements, etc. Verifiable non-functional requirement o Measures of requirements o E.g., Library users shall be able to use all the system functions after an one-hour training

Objects and Object Classes


Object: state, operations Object class: template Generalization and aggregation Identity objects, their attributes and services o Nouns and verbs

Modeling: class diagram


IS-A relationship HAS-A relationship

Modeling: use cases


Directed line: the user sends messages to the service Bi-directed line: the user sends to and receives messages from the service OR, we can use a line if we dont care about the directions of messages

Modeling: State Transition Diagram


Shows system states as nodes Show events as arcs between these nodes When an event occurs, the system moves from the one state to another

Class Association and Multiplicity


A semantic relationship between two or more classes that specifies connections among them Associations may be annotated with a label Multiplicity

15

Generalization and Aggregation


Generalization/Inheritance o This IS-A relationship o A sub-class inherits all attributes and operations from its super-class o As an abstraction mechanism: support reuse Aggregation o The HAS-A relationship o Shows how classes are composed of other classes

Sequence Diagram
Used to show the interactions between objects in the sequential order that those interactions occur Use cases are often refined into one or more sequence diagrams Made up of objects and messages The focus is less on messages themselves and more on the order in which messages occur Object: An instance of a class o An object is represented by a named rectangle o The name to the left of the : is the object and to its right is the class name Message: Interaction between different objects o A message is denoted by a directed arrow (annotated with descriptive text or operation name) Lifeline: Representing the life span of object during the scenario being modelled o The long, thin boxes on the lifelines are the activation boxes

CounterType an object of CounterType is used to count things, so it records a count that is a nonnegative integer number. It has mutators to increment by 1 and decrement by 1, but cannot go negative There is an accessor that returns the count value, and a display function that displays it.

Lecture 6

16

Inheritance
General form of class is defined o Specialized versions then inherit properties of general class o Add to it/modify its functionality for its appropriate use New class inherited from another class called Base class o General class from which others derive Derived class o New class o Automatically has base classs: Member variables Member functions o Can add additional member functions and varaibles

Inheritance Terminology
Common to simulate family relationships Parent Class o Refers to base class Child Class o Refers to derived class Ancestor class o Class thats a parent of a parent Descendant class o Class thats a child of a child

Constructors in Derived Class


Base class constructors are NOT inherited in derived classes but can be invoked within derived class constructors Base class constructor must initialize all base class member variables which will be inherited by the derived class whose constructor simply calls it

Private Data
Derived class inherits private member variables but cannot directly access them even through derived member functions Can only access the variable by name in member functions of the class they are defined in Private member functions cannot be accessed outside interface and implementation of base class therefore making them simply not available

17

The Protected: Qualifier


New classification of class members Allows access by name in derived class but nowhere else In class its defined acts like private member Considered protected in derived class to allow future derivations Many feel this violates information hiding

Redefinition of Member Functions


Recall interface of derived class: o Contains declarations for new member functions o Also contains declarations for inherited member functions to be changed o Inherited member functions NOT declared: Automatically inherited unchanged Implementation of derived class will: o Define new member functions o Redefine inherited functions as declared

Redefining verse Overloading


Redefining in derives class: o SAME parameter list o Essentially re-writes the same function o Base definition is not lost when redefined Overloading: o Different parameter list o Defined new functions that takes different parameters o Overloaded functions must have different signatures

Function Signature
Signature o Functions name o Sequence of types in parameter list Including order, number, types Signature does NOT include: o Return type o Const keyword o &

18

Functions Not Inherited


Normal functions are inherited Exceptions: o Constructors o Destructors o Copy constructor But if not defined, generates a default one Recall need to define on for pointers o Assignment operator If not defined default

Assignment Operators and Copy Constructors


Overloaded assignment operators and copy constructors are not inherited o Can be used in derived class definitions o Typically MUST be used! o Similar to how derived class constructor invokes base class constructor

Destructors in Derived Classes


If base class destructor functions correctly o Easy to write derived class destructor When derived class destructor is invoked: o Automatically calls base class destructor o So no need for explicit call So derived class destructors need only be concerned with derived class variables o Any data they point to o Base class destructor handles inherited data automatically

Destructor Calling Order


Consider: Class B derives from class A Class C derives from class B ABC When object of class C goes out of scope: o Class C destructor called 1st o Then class B destructor called o Finally class A destructor is called Opposite as to how constructors are called

19

Is a vs Has a Relationships
Inheritance o Considered an Is a class relationship o E.g. An HourlyEmployee is a Employee o A Convertible is a Automobile A class contains objects of another class as its member data o Considered a Has a class relationship o E.g., One class has a object of another class as its data

Protected and Private Inheritance


New inheritance forms Protected inheritance: o Public variables in base class become protected in derived class o E.g. class SalariedEmployee : protected Employee Private inheritance: o All members in base class become private in derived class o E.g. class SalariedEmployee : private Employee

Multiple Inheritances
Derived class can have more than one base class o Syntax includes all base classes separated by commas Possibilities for ambiguity are endless Dangerous undertaking o Believed that is should never be used

Summary
Inheritance provides code reuse o Allows one class to derive from another, adding features Derived class objects inherit members of base class o And may add members Private member variables in base class cannot be accessed by name in derived Private member functions are not inherited Can redefine inherited member functions o To perform differently in derived class Protected members in base class:

20 o Can be accessed by name in derived class member functions Overloaded assignment operator not inherited o Can be invoked from derived class Constructors are not inherited o Are invoked from derived classs constructor

Lecture 7
Virtual Function Basics
Polymorphism o Associating many meanings to one function o Virtual functions provide this capability o Fundamental principle of object-oriented programming Virtual o Existing in essence though not in fact Virtual Function o Can be used before its defined

Figures Example
Best explained by example: Classes for several kinds of figures Rectangles, circles, ovals, etc. Each figure an object of different class Rectangle data: height, width, center point Circle data: center point, radius All derive from one parent-class: Figure Require function: draw() Different instructions for each figure

Figures Example 2
Each class needs different draw function Can be called "draw" in each class, so: Rectangle r;

21 Circle c; r.draw(); //Calls Rectangle classs draw c.draw(); //Calls Circle classs draw Nothing new here yet

Figures Example: center()


Parent class Figure contains functions that apply to "all" figures; consider: center(): moves a figure to center of screen Erases 1st, then re-draws So Figure::center() would use function draw() to re-draw Complications! Which draw() function? From which class?

Figures Example: New Figure


Consider new kind of figure comes along:Triangle class derived from Figure class Function center() inherited from Figure Will it work for triangles? It uses draw(), which is different for each figure! It will use Figure::draw() wont work for triangles Want inherited function center() to use function Triangle::draw() NOT function Figure::draw() But class Triangle wasnt even WRITTEN when Figure::center() was! Doesnt know "triangles"!

Figures Example: Virtual


Tells compiler: o Dont know how function is implemented, wait until used in program o Then get implementation from object instance Called late binding or dynamic binding o Virtual functions implement late binding

Virtual Functions: Another Example


Bigger example best to demonstrate Record-keeping program for automotive parts store

22 Track sales Dont know all sales yet 1st only regular retail sales Later: Discount sales, mail-order, etc. Depend on other factors besides just price, tax

Virtual Functions: Auto Parts


Program must: Compute daily gross sales Calculate largest/smallest sales of day Perhaps average sale for day All come from individual bills But many functions for computing bills will be added "later"! When different types of sales added! So function for "computing a bill" will be virtual!

Class Sale Definition


class Sale { public: Sale(); Sale(double thePrice); double getPrice() const; virtual double bill() const; double savings(const Sale& other) const; private: double price; };

Member Functions
savings and operator < double Sale::savings(const Sale& other) const { return (bill() other.bill());

23 } bool operator < ( const Sale& first, const Sale& second) { return (first.bill() < second.bill()); } Notice BOTH use member function bill()!

Class Sale
Represents sales of single item with no added discounts or charges. Notice reserved word "virtual" in declaration of member function bill Impact: Later, derived classes of Sale can define THEIR versions of function bill Other member functions of Sale will use version based on object of derived class! They wont automatically use Sales version!

Derived Class DiscountSale Defined


class DiscountSale : public Sale { public: DiscountSale(); DiscountSale( double thePrice, double the Discount); double getDiscount() const; void setDiscount(double newDiscount); double bill() const; private: double discount; };

DiscountSales Implementation of bill()


double DiscountSale::bill() const { double fraction = discount/100; return (1 fraction)*getPrice(); } Qualifier "virtual" does not go in actual function definition

24 "Automatically" virtual in derived class Declaration (in interface) not required to have "virtual" keyword either (but usually does) Virtual function in base class: "Automatically" virtual in derived class Derived class declaration (in interface) Not required to have "virtual" keyword But typically included anyway, for readability

Derived Class DiscountSale


DiscountSales member function bill() implemented differently than Sales Particular to "discounts" Member functions savings and "<" Will use this definition of bill() for all objects of DiscountSale class! Instead of "defaulting" to version defined in Sales class

Virtual: Wow!
Recall class Sale written long before derived class DiscountSale Members savings and "<" compiled before even had ideas of a DiscountSale class Yet in a call like: DiscountSale d1, d2; d1.savings(d2); Call in savings() to function bill() knows to use definition of bill() from DiscountSale class Powerful!

Virtual: How?
To write C++ programs: Assume it happens by "magic"! But explanation involves late binding Virtual functions implement late binding Tells compiler to "wait" until function is used in program Decide which definition to use based on calling object Very important

25

Overriding
Virtual function definition changed in a derived class o We say its been overridden Similar to redefined o Recall: for standard functions So: o Virtual functions changed: overridden o Non-virtual function changed: redefined

Virtual Functions: Why Not All?


Clear advantages to virtual functions as seen One major disadvantage: overhead o Uses more storage o Late binding is on the fly, so programs run more slowly So if virtual functions are not needed, they should not be used

Pure Virtual Functions


Base class might not have meaningful definition for some of its members o Its purpose solely for other to derive from Recall class figure o All figures are objects of derived class Rectangles, circles, triangles, etc o Class figure has no idea how to draw Make it a pure virtual function: o Virtual void draw() = 0;

Abstract Base Classes


Pure virtual functions require no definition o Forces all derived classes to define their own version Class with one or more pure virtual function is: abstract base class o Can only be used as base class o No objects can ever be created from it Since it doesnt have complete definitions of all its members If derived class fails to define all pure virtual functions:

26 o Its an abstract base class too

Extended Type Compatibility


Given: Derived is derived class of Base Derived objects can be assigned to objects of type Base But NOT the other way! Consider previous example: A DiscountSale "is a" Sale, but reverse not true

Extended Type Compatibility Example


class Pet { public: string name; virtual void print() const; }; class Dog : public Pet { public: string breed; virtual void print() const; };

Classes Pet and Dog


Now given declarations: Dog vdog; Pet vpet; Notice member variables name and breed are public! For example purposes only! Not typical!

Using Classes Pet and Dog


Anything that "is a" dog "is a" pet: vdog.name = "Tiny"; vdog.breed = "Great Dane"; vpet = vdog;

27 These are allowable Can assign values to parent-types, but not reverse A pet "is not a" dog (not necessarily)

Casting
Consider: Pet vpet; Dog vdog; vdog = static_cast<Dog>(vpet); //ILLEGAL! Cant cast a pet to be a dog, but: vpet = vdog; // Legal! vpet = static_cast<Pet>(vdog); //Also legal! Upcasting is OK From descendant type to ancestor type

Downcasting
Still dangerous Assumes information is added and is rarely done due to pitfalls o Must track all information to be added o All member functions must be virtual

Can be done with dynamic_cast: Pet *ppet; ppet = new Dog; Dog *pdog = dynamic_cast<Dog*>(ppet); Legal, but dangerous!

Slicing Problem
Notice value assigned to vpet "loses" its breed field! cout << vpet.breed; Produces ERROR msg! Called slicing problem Might seem appropriate Dog was moved to Pet variable, so it should be treated like a Pet And therefore not have "dog" properties Makes for interesting philosophical debate

28

Slicing Problem Example


Pet *ppet; Dog *pdog; pdog = new Dog; pdog->name = "Tiny"; pdog->breed = "Great Dane"; ppet = pdog; Cannot access breed field of object pointed to by ppet: cout << ppet->breed; //ILLEGAL!

Slicing Problem Example


Must use virtual member function: ppet->print(); Calls print member function in Dog class! Because its virtual C++ "waits" to see what object pointer ppet is actually pointing to before "binding" call

Slicing Problem
Occurs when assign values to child-types In C++, slicing problem is a nuisance Can be fixed with pointers to dynamic variables

Virtual Destructors
Recall: destructors needed to de-allocate dynamically allocated data All destructors can be virtual and it is good to do so

Inner Workings of Virtual Functions


Dont need to know how to use it o Principle of information hiding Virtual function table o Compiler creates it o Has pointers for each virtual member function o Points to location of correct code for that function Objects of such classes also have pointer o Points to virtual function table

29

Summary
Late binding delays decision of which member function is called until runtime o In C++, virtual functions use late binding Pure virtual functions have no definition o Classes with at least one are abstract o No objects can be created from abstract class o Used strictly as base for others to derive Derived class objects can be assigned to base class objects o Base class members are lost; slicing problem Pointer assignments and dynamic objects o Allow fix to slicing problem Make all destructors virtual o Good programming practice o Ensures memory correctly de-allocated

Lecture 8
Templates
C++ templates o Allow very general definitions for functions and classes o Type names are parameters instead of actual types o Precise definition determined at run-time

Recall function swapValues: void swapValues(int& var1, int& var2) { int temp; temp = var1; var1 = var2; var2 = temp; } Applies only to variable of type int But code would work for all types

Function Templates vs. Overloading


Could overload function for chars:

30 void swapValues(char& var1, char& var2) { char temp; temp = var1; var1 = var2; var2 = temp; } But notice: code is nearly identical (Only difference is type used in 3 places

Function Template Syntax


Allow swap values of any type variables: template <Class T> { T temp; temp = var1; var1 = var2; var2 = temp; } First line called template prefix o Tells compilers whats coming is template o And that T is a type parameter

Template Prefix
Recall: template<class T> In this usage class means type , or classification Can be confused with other known use of word class! o C++ allows keyword typename in place of keyword class here o But most use class anyway T can be replaced by any type o Predefined or user-defined like a C++ class type In function definition body: o T used like any other type Note: can use other than T, but T is traditional usage

Function Template Definition


swapValues() function template is actually a large collection of definitions

31 o A definition for each possible type Compiler only generates definitions when required o But its as if youd defined for all types o Write one definition works for all types that might be needed

Calling a Function Template


Consider following call: swapValues(int1, int2); o C++ compiler generates function definition for two int parameters using template Likewise for all other types Neednt do anything special in call o Required definition automatically generated

Another Function Template


Declaration/prototype: Template<class T> void showStuff(int stuff1, T stuff2, T stuff3); Definition: template<class T> void showsStuff(int stuff1, T stuff2, T stuff3) { Cout << stuff1<<endl <<stuff2<<endl <stuff3<<endl;

showStuff Call
Consider function call: showStuff(2,3.3,4.4); Compiler generates function definition o Replaces T with double Since second parameter is type double Displays the values accordingly

Compiler Complications
Function declarations and definitions

32 o Typically we have them separate o For templates not supported on most compilers! Safest to place template function definition in file where invoked o Many compilers require it appears 1st o Often we #include all template definitions

More Compiler Complications


Check your compilers specific requirements o Some need to set special options o Some require special order of arrangement of template definition vs. other file items Most usable template program layout: o Template definition in same file its used o Ensure template definition precedes all uses Can #include it Can have: template<class T1, class T2> Not typical o Usually only need one replaceable type o Cannot have unused template parameters Each must be used in definition Error otherwise!

Algorithm Abstraction
Refers to implementing templates Express algorithms in general way: o Algorithm applies to variable of any type o Ignore incidental detail o Concentrate on substantive parts of algorithm Function templates are one way C++ supports algorithm abstraction

Defining Templates Strategies


Develop function normally o Using actual data types Completely debug ordinary function Then convert to template

33 o Replace type names with type parameter as needed Advantages o Easier to solve concrete case o Deal with algorithm, not template syntax

Inappropriate Types in Templates


Can use any type in template for which code makes sense o Code must behave in appropriate way E.g., swapValues() template function o Cannot use type for which assignment operator isnt defined o Example: an array: Int a[10], b[10]; swapValues(a,b); - Arrays cannot be assigned

Class Templates
Can also generalize classes template <class T> o Can also apply to class definition o All instances of T in class definition replaces by type parameter o Just like for function templates Once template defined, can declare objects of the class

Class Template Definition


template<class T> class Pair { public: Pair(); Pair(T firstVal, T secondVal); void setFirst(T newVal); void setSecond(T newVal); T getFirst() const; T getSecond() const; private: T first; T second; };

34

Template Class Pair Members


template<class T> Pair<T>::Pair(T firstVal, T secondVal) { first = firstVal; second = secondVal; } template<class T> void Pair<T>::setFirst(T newVal) { first = newVal; }

Template Class Pair


Objects of class have pair of values of type T Can then declare objects: Pair<int> score; Pair<char> seats; o Objects then used like any other objects Examples use: score.setFirst(3);

Pair Member Function Definitions


Notice in member function definitions: o Each definition itself a template o Requires template prefix before each definition o Class name before :: is Pair<T> (Not just Pair:) But constructor name is just Pair Destructor name also just ~Pair

Class Templates as Parameters


Consider: int addUP(const Pair<int>& the Pair); o The type (int) is supplied to be used for T in defining this class type parameters o It happens to be call-by-reference here

35 Again; template types can be used anywhere standard types can

Class Templates Within Function Templates


Rather than defining new overload: template<class T> T addUp(const Pair<T>& the Pair);

//Precondition: Operator + is defined for values of type T //Returns sum of two values in thePair Function now applies to all kinds of numbers

Restriction on Type Parameter


Only reasonable types can be substituted for T Consider: o Assignment operator must be well-behaved o Copy constructor must also work o If T involves pointers, then destructor must be suitable Similar issues as function templates

Type Definitions
Can define new class type name o To represent specialized class template name Example: typedef Pair<int> PairOfInt; Name PairOfInt now used to declare objects of type Pair<int>: PairOfInt pair1, pair2; Name can also be used as parameter, or anywhere else type name allowed

Friends and Templates


Friend functions can be used with template classes o Same as with ordinary classes o Simply requires type parameter where appropriate Very common to have friends of template classes o Especially for operator overloads (as weve seen)

36

Predefined Template Classes


Recall vector class o Template class Another: basic_string template class o Deals with strings of any-type elements: Basic_string<char> works for chars <double> works for doubes <YourClass> works for class objects Basic_String Template Class Already used it; Recall string o Its an alternate name for basic_string<char> o All member functions behave similarly for basic_string<T> Basic_string defined in library <string> o Definition is in std namespace

Templates and Inheritance


Derived template classes o Can derive from template of nontemplate class o Derived class is then naturally a template class Syntax same as ordinary class derived from ordinary class

Summary
Function templates o Define functions with parameters for a type Class templates o Define class with parameter for subparts of class Predefined vector and basic_string classes are template classes Can define template class derived from a template base class

Lecture 9
Exception Handling Basics
Meant to be used sparingly o In involved situations

37

Toy Example
Imagine: people rarely run of milk: cout << "Enter number of donuts:"; cin >> donuts; cout << "Enter number of glasses of milk:"; cin >> milk dpg = donuts/static_cast<double>(milk); cout << donuts << "donuts.\n"; << milk << "glasses of milk.\n"; << "You have " << dpg << "donuts for each glass of milk.\n"; Code assumes milk never runs out Notice: If no milk divide by zero error! Program should accommodate unlikely situation of running out of milk o Can use a simple if else structure where there is no exception handling If (milk<=0) Cout << Go buy some milk!\n; Else {}

Example with Exception Handling

38

Toy Example try-catch


Try block o Handles normal situation Catch block o Handles exceptional situations Provides separation of normal from exceptional

Try Block
Basic method of exception-handling is try-throw-catch Try block:

Try { Some_code; } Contains code for basic algorithm when all goes smoothly

Throw
Inside try-block, when something unusual happens:

Try { Code_to_try If (exception_happens) Throw donuts; More_code } Keyword throw followed by exception type Called throwing an exception

Catch-Block
When something thrown goes somewhere o In C++, flow of control goes from try-block to catch-block Try-block is exited and control passes to catch-block o Executing catch block called catching the exception Exceptions must be handled in some catch block

39

Catch-Block Parameter
Using catch(int e) o e called catch-block parameter Each catch block can have at most ONE parameter Does two things: o 1. Type name specifies what kind of thrown value the catch-block can catch o 2. Provides name for thrown value caught; can do things with value

Defining Exception Classes


Throw statement can throw value of any type Exception class o Contain objects with information to be thrown o Can have different types identifying each possible exceptional situation o Still just a class An exception class due to how its used

Exception Class for Toy Example


Consider Class NoMilk { public: NoMilk() { } NoMilk(int howMany) : count(howMany) { } int getcount() const { return count; } private: int count; }; Throw NoMilk(donuts); o Invokes constructor of NoMilk class

Multiple Throws and Catches


Try-block typically throws any number of exception values, of differing types Of course only one exception thrown o Since throw statement ends try-block But different types can be thrown o Each catch block only catches one type o Typical to place many catch-blocks after each try-block

40 To catch all-possible exceptions to be thrown

Catching
Order of catch blocks important Catch-blocks tried in order after try-block o First match handles it! Consider: catch(){ } o Called catch-all, default exception handler o Catches any exception o Ensure catch-all placed AFTER more specific exceptions Or others will never be caught!

Throwing Exception In Function


Function might throw exception Callers might have different reactions o Some might desire to end program o Some might continue, or do something else Makes sense to catch exception in calling functions try-catch-block o Place call inside try-block o Handle in catch-block after try-block

Exception Specification
Functions that dont catch exceptions o Should warn users that it could throw o But it wont catch! Should list such exceptions: double safeDivide(int top, int bottom) throw (DividebyZero) o Called exception specification or throw list o Should be in declaration and definition o All types listed handled normally o If no throw list all types considered there

Throw List
If exception thrown in function NOT in throw list: o No errors (compile or run-time)

41 o Function unexpected() automatically called Default behaviour is to terminate Can modify behavior Same result if no catch-block found

Throw List Summary


void someFunction() throw(DividebyZero, OtherException); //Exception types DividebyZero or OtherException //treated normally. All others invoke unexpected() void someFunction() throw (); //Empty exception list, all exceptions invoke unexpected() void someFunction(); //All exceptions of all types treated normally

Derived Classes
Remember: derived class objects also objects of base class Consider: D is derived class of B If B is in exception specification o Class D thrown objects will also be treated normally, since its also object of class B Note: does not do automatic type cast: o Double will not account for throwing an int

Unexpected()
Default action: terminate program o No special includes or using directives Normally no need to redefine But you can: o Use set_unexpected o Consult compiler manual or advanced text for details

When to Throw Exceptions


Typical to separate throws and catches o In separate functions Throwing function:

42 o Include throw statements in definition o List exceptions in throw list In both direction and definition Catching function: o Different function, perhaps even in different file

Uncaught Exceptions
Should catch every exception thrown If not program terminates o Terminate() is called Recall for functions o If exception not in throw list: unexpected() is called It in turn calls terminate() So same result

Rethrowing an Exception
Legal to throw exception IN catch-block! o Typically only in rare cases Throws to catch-block farther up chain Can re-throw same or new exception o Rethrow; Throws same exception again o Throw newExcetpionUp; Throws new exception to next catch-block

Summary
Exception handling allows separation of normal cases and exceptional cases Exceptions thrown in try-block o Or within a function whose call is in try-block Exception caught in catch-block Try-blocks typically followed by more than one catch-block o List more specific exceptions first Best used with separate functions o Especially considering callers might handle differently Exceptions thrown in but not caught in function, should be listed in throw list Exceptions thrown but never caught program terminates Resist overuse of exceptions

43 o Unrestricted flow of control

Lecture 10
Iterators
Recall: generalization of a pointer o Typically even implemented with pointer Abstraction of iterators o Designed to hide details of implementation o Provide uniform interface across different container classes Each container class has own iterator type o Similar to how each data type has own pointer type

Manipulating Iterators
Recall using overloaded operators: o ++, --, ==, !=, * So if p is an iterator variable, *p gives access to data pointed to by p Vector template class o Has all above overloads o Also has members begin() and end() c.begin(); //Returns iterator for 1st item in c c.end(); //Return test value for end

Cycling with Iterators


Recall cycling ability: for (p=c.begin();p!=c.end();p++) process *p //*p is current data item Keep in mind: o Each container type in STL has own iterator types Even though theyre all used similarly

Vector Iterator Example


//Program to demonstrate STL iterators. 2 #include <iostream> 3 #include <vector> 4 using std::cout;

44 5 using std::endl; 6 using std::vector; 7 int main( ) 8{ 9 vector<int> container; 10 for (int i = 1; i <= 4; i++) 11 container.push_back(i); 12 cout << "Here is what is in the container:\n"; 13 vector<int>::iterator p; 14 for (p = container.begin( ); p != container.end( ); p++) 15 cout << *p << " "; 16 cout << endl; 17 cout << "Setting entries to 0:\n"; 18 for (p = container.begin( ); p != container.end( ); p++) 19 *p = 0; 20 cout << "Container now contains:\n"; 21 for (p = container.begin( ); p != container.end( ); p++) 22 cout << *p << " "; 23 cout << endl; 24 return 0; 25 } SAMPLE DIALOGUE Here is what is in the container: 1234 Setting entries to 0: Container now contains: 0000

Vector Iterator Types


Iterators for vectors of ints are of type: std::vector<int>::iterator Iterators for lists of ints are of type: std::list<int>::iterator Vector is in std namespace, so noeed: using std::vector<int>::iterator;

45

Kinds of Iterators
Different containers different iterators Vector iterators o Most general form o All operations work with vector iterators o Vector container great for iterator examples

Bidirectional and Random-Access Iterator Use

Iterator Classifications
Forward iterators: o ++ works on iterator Bidirectional iterators o Both ++ and -- work on iterator Random-access iterators o ++, --, and random access all work with iterator

46

Constant and Mutable Iterators


Dereferencing operators behavior dictates Constant iterator: o * produces read-only version of element o Can use *p to assign to variable or output, but cannot change element in container Mutable iterator o *p can be assigned value o Change corresponding element in container o i.e.: *p returns an Ivalue

Reverse Iterators
To cycle elements in reverse order o Requires container with bidirectional iterators Might consider: iterator p; for (p=container.end():p!=container.begin():p--) cout << *p << ; o But recall: end() is just sentinel, begin() is not o Might work on some systems, but not most

Reverse Iterators Correct


To correctly cycle elements in reverse order: reverse_iterator p; for (rp=container.rbegin();rp!=container.end();rp++) cout << *rp << ; Rbegin() o Returns iterator at last element Rend() o Return sentinel end maker

Iterator Compiler Problems


Some compilers problematic with iterator declarations Consider our usage: using std::vector<char>::iterator; . iterator p;

47 Alternatively: std::vector<char>::iterator p; And others. o Try various forms if compiler problematic

Containers
Container classes in STL o Different kinds of data structures o Like lists, queues, stacks Each is template class with parameter for particular data type to be stored o E.g., List of ints, double or myClass types Each has own iterators o One might have bidirectional, another might just have forward iterators But all operators and members have same meaning

Sequential Containers
Arranges list data o 1st element, next element,. To last element Linked list is sequential container o Earlier linked lists were singly linked lists One link per node STL has no singly linked list o Only doubly linked list: template class list

Example for Using List Template Class


//Program to demonstrate the STL template class list. 2 #include <iostream> 3 #include <list> 4 using std::cout; 5 using std::endl; 6 using std::list; 7 int main( ) 8{ 9 list<int> listObject; 10 for (int i = 1; i <= 3; i++) 11 listObject.push_back(i); 12 cout << "List contains:\n"; 13 list<int>::iterator iter;

48 14 for (iter = listObject.begin( ); iter != listObject.end( ); iter++) 15 cout << *iter << " "; 16 cout << endl; 17 cout << "Setting all entries to 0:\n"; 18 for (iter = listObject.begin( ); iter != listObject.end( ); iter++) 19 *iter = 0; 20 cout << "List now contains:\n"; 21 for (iter = listObject.begin( ); iter != listObject.end( ); iter++) 22 cout << *iter << " "; 23 cout << endl; 24 return 0; 25 } SAMPLE DIALOGUE List contains: 123 Setting all entries to 0: List now

Container Adapters stack and Queue


Container adapters are template classes o Implemented on top of other classes Example: stack template class by default implemented on top of deque template class o Buried in stacks implementation is deque where all data resides Others: queue, priorite_queue

Specifying Containers Adapters


Adapter templates have default containers underneath o But can specify different underlying containers o Examples: stack template class any sequence container priority_queue default is vector, could be others Implementing Example: stack<int, vector<int> > (note the space between <int> and >) o Makes vector underlying container for stack

49

Associative Containers
Associative container: simple database Store data o Each data item has key Example: data: employees record as struct key: employees SSN o Items retrieved based on key

Set Template Class


Simplest container possible Stores elements without repetition 1st insertion places element in set Each element is own key Capabilities: o Add elements o Delete elements o Ask if element is in set

More Set Template Class


Designed to be efficient o Stores values in sorted order o Can specify order: set<T, Ordering> s; Ordering is well-behaved ordering relation that returns bool None specified: use < relational operator

Program Using Set Template Class


1 //Program to demonstrate use of the set template class. 2 #include <iostream> 3 #include <set> 4 using std::cout; 5 using std::endl; 6 using std::set; 7 int main( ) 8{ 9 set<char> s; 10 s.insert(A); 11 s.insert(D);

50 12 s.insert(D); 13 s.insert(C); 14 s.insert(C); 15 s.insert(B); 16 cout << "The set contains:\n"; 17 set<char>::const_iterator p; 18 for (p = s.begin( ); p != s.end( ); p++) 19 cout << *p << " "; 20 cout << endl; 21 cout << "Set contains 'C': "; 22 if (s.find('C')==s.end( )) 23 cout << " no " << endl; 24 else 26 cout << " yes " << endl; 27 cout << "Removing C.\n"; 28 s.erase(C); 29 for (p = s.begin( ); p != s.end( ); p++) 30 cout << *p << " "; 31 cout << endl; 32 cout << "Set contains 'C': "; 33 if (s.find('C')==s.end( )) 34 cout << " no " << endl; 35 else 36 cout << " yes " << endl; 37 return 0; 38 } SAMPLE DIALOGUE The set contains: ABCD Set contains 'C': yes Removing C. ABD Set contains 'C': no

Map Template Class


A function given as set of ordered pairs o For each value first, at most one value second in map Example map declaration: map<string, int>numberMap;

51 Can use [] notation to access the map o For both storage and retrieval Stores in sorted order, like set o Second value can have no ordering impact

Program Using the Map Template


1 //Program to demonstrate use of the map template class. 2 #include <iostream> 3 #include <map> 4 #include <string> 5 using std::cout; 6 using std::endl; 7 using std::map; 8 using std::string; 9 int main( ) 10 { 11 map<string, string> planets; 12 planets["Mercury"] = "Hot planet"; 13 planets["Venus"] = "Atmosphere of sulfuric acid"; 14 planets["Earth"] = "Home"; 15 planets["Mars"] = "The Red Planet"; 16 planets["Jupiter"] = "Largest planet in our solar system"; 17 planets["Saturn"] = "Has rings"; 18 planets["Uranus"] = "Tilts on its side"; 19 planets["Neptune"] = "1500 mile per hour winds"; 20 planets["Pluto"] = "Dwarf planet"; 21 cout << "Entry for Mercury - " << planets["Mercury"] 22 << endl << endl; 23 if (planets.find("Mercury") != planets.end()) 24 cout << "Mercury is in the map." << endl; 25 if (planets.find("Ceres") == planets.end()) 26 cout << "Ceres is not in the map." << endl << endl; 27 cout << "Iterating through all planets: " << endl; 28 map<string, string>::const_iterator iter; 29 for (iter = planets.begin(); iter != planets.end(); iter++) 30 { 31 cout << iter->first << " - " << iter->second << endl; 32 } The iterator will output the map in order sorted by the key. In this case the output will be listed alphabetically by planet.

52 33 return 0; 34 }

Efficiency
STL designed with efficiency as important consideration o Strives to be optimally efficient Example: set, map elements stored in sorted order for fast searches Template class member functions: o Guaranteed maximum running time o Called Big-O notation, an efficiency rating

Generic Algorithms
Basic template functions Recall algorithm definition: o Set of instructions for performing a task o Can be represented in any language o Typically thought of in pseudocode o Considered abstraction of code Gives important details, but not find code details STLs algorithms in template functions: o Certain details provided only Therefore considered generic algorithms

Running Times
Produce table o Based on input size o Table called function in math With arguments and return values o Argument is input size: T(10), T(10,000),. Function T is called running time

53

Counting Operations
T(N) given by formula, such as: T(N) = 5n+5 o On inputs of size N program runs for 5N+5 time units Must be computer-independent o Doesnt matter how fast computers are o Cant count time o Instead count operations

Counting Example
int I = 0; bool found = false; while (( I < N) && !found) if (a[I] == target) found = true; else I++; 5 operations per loop iteration: <, &&, !, [ ], ==, ++ After N iterations, final three: <, &&, ! So: 6N+5 operations when target not found

Big-O Notation
Recall: 6N+5 operations in worst-case Expressed in Big-O notation o Some constant c factor where c(6N+5) is actual running time C different on different systems o We say code runs in time O(6N+5) o But typically only consider highest term Term with highest exponent

54 o O(N) here

Big-O Terminology
Linear running time: o O(N) directly proportional to input size N Quadratic running time: o O(N^2) Logarithmic running time: o O(log N) Typically log base 2 Very fast algorithms!

Container Access Running Times


O(1) constant operation always: o Vector inserts to front or back o Deque inserts o List inserts O(N) o Insert or delete of arbitrary element in vector or deque (N is number of elements) O(log N) o Set or map finding

55

Nonmodifying Sequence Algorithms


Template functions operating on containers o No modification of container contents Generic find function o Typical example o Can be used with any STL sequence container class

Generic Find Function Example


1 //Program to demonstrate use of the generic find function. 2 #include <iostream> 3 <vector> 4 #include <algorithm> 5 using std::cin; 6 using std::cout; 7 using std::endl; 8 using std::vector; 9 using std::find; 10 int main( ) 11 { 12 vector<char> line; 13 cout << "Enter a line of text:\n"; 14 char next; 15 cin.get(next); 16 while (next != \n) 17 { 18 line.push_back(next); 19 cin.get(next); 20 } 21 vector<char>::const_iterator where; 22 where = find(line.begin( ), line.end( ), e); 23 //where is located at the first occurrence of e in v. 24 vector<char>::const_iterator p; 25 cout << "You entered the following before you entered your first e:\n"; 26 for (p = line.begin( ); p != where; p++) 27 cout << *p; 28 cout << endl; 29 cout << "You entered the following after that:\n"; 30 for (p = where; p != line.end( ); p++)

56 31 cout << *p; 32 cout << endl; 33 cout << "End of demonstration.\n"; 34 return 0; 35 }

Modifying Sequence Algorithms


STL functions that change container contents Recall: adding/removing elements from containers can affect other iterators! o List, slist guarantee no iterator changes o Vector, deque make NO such guarantee Always watch which iterators are assured to be changed/unchanged

Set Algorithms
STL generic set operation functions All assume containers stored in sorted order Containers set, map, multiset, multimap o DO store in sorted order, so all set functions apply Others, like vector, are not sorted o Should not use set functions

Sorting Algorithms
STL contains two template functions: o 1. Sort range of elements o 2. Merge two sorted ranges of elements Guaranteed running time O(N log N) o No sort can be faster o Function guarantees fastest possible sort

Summary
Iterator is generalization of a pointer o Used to move through elements of container Container classes with iterators have: o Member functions end() and begin() to assist cycling Main kinds of iterators: o Forward, bi-directional, random-access Given constant iterators p, *p is read-only version of element Given mutable iterator p *p can be assigned value

57 Bidirectional container has reverse iterators allowing reverse cycling Main STL containers list, vector, deque o Stack, queue: container adapter classes Set, map, multiset, multimap containers store in sorted order STL implements generic algorithms o Provide maximum running time guarantees

58

Vasa Case Study Table

59

Sample Questions
Q3: What is three-tier architecture? a) Presentation, Object and Data b) Interface, Middleware and Information c) Presentation, Class and Knowledge d) None of the above ANS: d Q4: Which of the following statement is illegal? struct CDAccount { double balance, interestRate; int term; }; CDAccount account1; a) account1.balance = 1500; b) account1.interestRate = 15.00; c) account1.balance = account1.term; d) None of the above ANS: d Sample Question The ability to reuse objects already defined, perhaps for a different purpose, with modification appropriate to the new purpose, is referred to as: a) Information hiding b) Inheritance c) Redefinition d) Overloading Answer: b) Inheritance Sample MC Question 2 (1.5%) If a class B is a pubic base class for a derived class D, then an object of class D bears what relationship to class B? a) A has-a relationship b) A fraternal relationship c) An is-a relationship d) There is no relationship here. Answer: c)

60

Sample MC Question 3 (1.5%) Virtual functions are implemented with a table look up that is done at run time. a) True b) False c) False if you turn on the debugger d) None of the above Answer: a) Sample MC Question 4 (1.5%) How many type parameters may a function template have? a) none, that is not what the parameters in a function template are called. b) 1 c) 2 d) As many as are needed Answer: d) Sample MC Question 5 (1.5%) Consider the following C++ class declarations: How many public members does class Y have? a) 0 b) 1 c) 2 d) 3 Answer: d) Question 13: The Fibonacci numbers are the numbers in the following integer sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, and so on. In mathematical terms, the sequence Fn of Fibonacci numbers is de fined by the recurrence relation Fn = Fn1 + Fn 2 with seed values F1 = 1, F2 = 1. Here is the C++ codes to implement such a function. #include <iostream> using namespace std; /** Computes a Fibonacci number. @param n an integer @return the nth Fibonacci number */ int fib(int n) { if (n <= 2) { ____A____ }

61 int fold = 1; int fold2 = 1; int fnew; for (int i = 3; ____B____; i++) { fnew = fold + fold2; fold2 = fold; fold = fnew; } return fnew; } int main() { cout << "Enter n: "; int n; cin >> n; int f = fib(n); cout << "fib(" << n << ") = " << f << endl; return 0; } Question 1. What is the missing piece of code on ____A____? (a) return 0; (b) return 1; (c) return n; (d) None of the above ANSWER: b Question 2. What is the missing piece of code on ____B____? (a) i = n (b) i < n (c) i <= n (d) None of the above ANSWER: c Question 3. What is the running time of this program?

62 (a) O(1) (b) O(N) (c) O(N2 ) (d) None of the above ANSWER: b Question 4. What is the output of this program? class base { public: void baseFun(){ cout"from base"endl;} }; class deri:public base { public: void baseFun(){ cout "from derived"endl;} }; void SomeFunc(base *baseObj) { baseObj>baseFun(); } int main() { base baseObject; SomeFunc(&baseObject); deri deriObject; SomeFunc(&deriObject); } (a) from base from derived (b) from base from base (c) from derived from derived (d) from derived from base ANSWER: b

63

Question 5. A function does not have an exception specification at all,so exceptions are prohibited. (a) True (b) False (c) True if the debugger is turned on (d) None of the above ANSWER: b Question 6. An exception is propagated. (a) From a place where the error occurs to the handler in the catch block. (b) From the throw statement buried in the try block to the handler in the catch block. (c) From a throw statement, not in a try block to the handler in the catch block. (d) From the catch block to the try block. ANSWER: b Question 7. Which of the following are correct declarations of iterators for STL containers? You may assume that the proper header has been included and that a using directive makes the names from namespace std available. (a) vector<int>::iterator vecIterator; (b) deque<int>::iterator dequeIterator; (c) list<int>::iterator listIterator; (d) All of the above. ANSWER: d Question 8. Which of the following operations do bidirectional iterators have? (a) Overloaded operator++ to move the place the iterator points forward by one element. (b) Overloaded operator to move the place the iterator points backward by one element. (c) Overloaded operator== and operator!= to determine whether two iterators point to the s ame element. (d) All of the above ANSWER: d

64

Question 9. An object of a derived classtype has exactly one type,the type with which it was declared. (a) True (b) False (c) False if the debugger is turned off (d) None of the above ANSWER: b Sample Programming Questions Question 11 (20 Marks) Write the following C++ codes in .h and .cpp Define a class named Payment that contains a member variable amount of type float that stores the amount of the payment and appropriate accessor and mutator methods: setP ayment and getPayment. Also create a member function named paymentDetails that outputs an English sentence "The payment amount is " that describes the amount of the payment. (8 Mark s) Next define a class named CashPayment that is derived from Payment. This class sho uld redefine the paymentDetails function to indicate that the payment is in cash "The ca sh payment amount is ". Include appropriate constructor(s). (4 Marks) Define a class named CreditCardPayment that is derived from Payment. This class sho uld contain member variables for the name on the card, expiration date, and credit card nu mber. Include appropriate constructor(s). Finally, redefine the paymentDetails function to include all cr edit card information in the printout. (8 Marks) Payment, CashPayment, CreditCardPayment Suggestion Answer: //payment.cpp // //This program introduces inheritance through a problem of

65 // creating two types of Payments, Cash and Credit. The // PaymentDetails method outputs in English a sentence that describes // the payment. #include <iostream> #include <string> using namespace std; // Base class to store a payment amount and get a description class Payment { public: Payment(); Payment(float amount); void setPayment(float amount); float getPayment(); void paymentDetails(); private: float amount; }; // ====================== // Payment // Constructor to initialize amount to 0 // ====================== Payment::Payment() : amount(0) { } // ====================== // Payment // Constructor to initialize default amount // ====================== Payment::Payment(float amt) : amount(amt) { } // ====================== // payment accessor/mutator methods // ======================

66 void Payment::setPayment(float amt) { amount = amt; } float Payment::getPayment() { return amount; } // ====================== // paymentDetails // Outputs the payment information in English // ====================== void Payment::paymentDetails() { cout << "The payment amount is " << amount << endl;; } // -------------------------------// ----- ENTER YOUR CODE HERE ----// -------------------------------// First define class for CashPayment, derive from Payment class CashPayment : public Payment { public: CashPayment(); CashPayment(float amt); void paymentDetails(); }; // ====================== // CashPayment constructors, // just invokes base constructor. // ====================== CashPayment::CashPayment() : Payment() { }

67 CashPayment::CashPayment(float amt) : Payment(amt) { } // ====================== // paymentDetails // Outputs the payment information in English // ====================== void CashPayment::paymentDetails() { cout << "The cash payment amount is " << getPayment() << endl; }

// Next define class for CreditCardPayment, derive from Payment. // This could be made more flexible with mutator and accessor // methods for the name, expiration, and creditcard variables. class CreditCardPayment : public Payment { public: CreditCardPayment(); CreditCardPayment(float amt, string name, string expiration, string creditcard); void paymentDetails(); private: string name; string expiration; string creditcard; }; // ====================== // CreditCardPayment constructors, // just invokes base constructor and initialize variables. // ====================== CreditCardPayment::CreditCardPayment() : Payment() { name = ""; expiration = ""; creditcard = "";

68 } CreditCardPayment::CreditCardPayment(float amt, string name, string expiration, string creditcard) : Payment(amt) { this->name = name; this->expiration = expiration; this->creditcard = creditcard; } // ====================== // paymentDetails // Outputs the payment information in English // ====================== void CreditCardPayment::paymentDetails() { cout << "The credit card payment amount is " << getPayment() << endl; cout << "The name on the card is: " << name << endl; cout << "The expiration date is: " << expiration << endl; cout << "The credit card number is: " << creditcard << endl; } // -------------------------------// --------- END USER CODE -------// -------------------------------Question 12 (15 Marks) Referring to the C++ codes you built in Question 11, draw the class hierarchy diagram f or the three classes: Payment, CashPayment, and CreditCardPayment. (5 Marks) Turn the base classs member function named paymentDetails into a virtual function an d rewrite the C++ codes you built in Question. Briefly describe the differences between this dyn amic binding approach and the redefine approach in Question 13. (10 Marks) Suggestion Answer:

69 Study the lecture notes on dynamic binding and we will discuss it at the Revision Class on April 22, 2014 (Tuesday).

Exception Handling Example

70

Sample Diagrams
Draw a State Transition Diagram for operations of the radio described below. [Hint: The radio has four states, based on light status and sound status. Some events/stimuli may appear multiple times in the diagram.] Description of operations of the radio The radio has three touch-sensitive buttons marked: OFF, SOUND, LIGHT. It also has a decorative light and a loudspeaker. At the start, the radio produces no light and no sound. When the button SOUND is pressed, the loudspeaker is turned on (but the light status remains unchanged). When the button LIGHT is pressed, the light is turned on (but the loudspeaker status remains unchanged). When the button OFF is pressed, the radio produces no light and no sound.

71

72

73

Exercise 1.2 Solutions


Type Checking:
Referring to the source.cpp provided above an example of type checking is making sure that all the data types are assigned properly. The enum AccountType should be assigned the defined account types and not integers. AccoutType myType = chequing; // legal assignment AccountType myOtherType = 1; //compiler should not allow this

Style Checking:
Referring to the source.cpp provided above an example of style Checking would be if there was just use of the enum AccountType in a switch statement As we saw in lecture that having a switch statement without all the possible optio ns should not be allowed by the compiler. Here we just make sure we have a switch case for each AccountType optoin.

74

Input validation:
Referring to the source.cpp provided above there are many examples of input val idation. Anytime the user inputs a value this value must be validated so that we do not h ave any buffer overflow problems. For example if the user inputs the address we must a llocate enough space for the input and also validate that the size of the input has not be en exceeded.

Você também pode gostar