Lecture Study Note (1)

88
1 Lecture Study Note (Courtesy of Scott Cunningham) 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 Class’s Place..............................................11

Transcript of Lecture Study Note (1)

Page 1: Lecture Study Note (1)

1

Lecture Study Note (Courtesy of Scott Cunningham)

Good Luck ladies and gentlemen!

ContentsData, 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 Class’s Place...........................................................................................................11

Abstract Data Types.......................................................................................................11

Encapsulation.............................................................................................................11

Principles of OOP.......................................................................................................12

Public and Private Members.......................................................................................12

Accessor and Mutator Functions....................................................................................12

Page 2: Lecture Study Note (1)

2

Structures versus Classes..........................................................................................12

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

Page 3: Lecture Study Note (1)

3

Figures Example: Virtual................................................................................................21

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

DiscountSale’s 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

Page 4: Lecture Study Note (1)

4

Template Prefix..............................................................................................................30

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

Page 5: Lecture Study Note (1)

5

Exception Class for Toy Example...............................................................................39

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

Page 6: Lecture Study Note (1)

6

Set Template Class........................................................................................................49

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

Page 7: Lecture Study Note (1)

7

Lecture 4

Data, Capta, Information & Knowledge Data

o Facts we may or may not focus on

Captao 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

Knowledgeo 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

Page 8: Lecture Study Note (1)

8

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

o Different structs can have same name member variables

No conflicts

Page 9: Lecture Study Note (1)

9

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 functiono 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

o Objects containing data and operations

o In C++, variables of class type are objects

Page 10: Lecture Study Note (1)

10

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 function’s prototypeo Function’s 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, dayo 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 function’s definition (in next example) Refers to member data of class

o No qualifiers

Page 11: Lecture Study Note (1)

11

Functions used for all objects of the class will refer to “that object’s” data when invoked

Exaple: today,output() //Displays “today” object’s 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 Class’s Place Class is full-fledged type

o Just like data types int, double, etc

Can have variables of a class typeo We simply call them objects

Can have parameters of a class typeo Pass-by-value

o Pass-by-reference

Can use class type like any other type

Abstract Data Types “Abstract”

o Programmers don’t know details

Abbreviated “ADT”o Collection of data values together with set of basic operations defined for

the values ADT’s often “language-independent”

o We implement ADT’s in C++ with classes

C++ class “defines” the ADTo Other languages implement ADT’s as well

Encapsulation Means “bringing together as one” Declare a class get an object

Page 12: Lecture Study Note (1)

12

Object is “encapsulation” ofo 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 abstractiono Details of how data is manipulated within ADT/class now known to user

Encapsulationo 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 functionso Allow object to change data

o Manipulated based on application

User of class need not see details of how class is implementedo 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

o Typically all members public

Page 13: Lecture Study Note (1)

13

o No member functions

Classeso Typically all data members are private

o Interface member functions public

Technically, sameo Perceptionally, very different mechanisms

Focus for programming changeso Before algorithms center stage

o OOP data is focus

Algorithms still existo They simply focus on their data

o Are “made” to “fit” the data

Designing software solutiono 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 function’s 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:

Page 14: Lecture Study Note (1)

14

o Functional requirements

o Non-functional requirements

o Domain requirements

Non-functional requirementso Product, organization, external requirements

o E.g. usability, process standard, legislative requirements, etc.

Verifiable non-functional requiremento 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 don’t 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

Page 15: Lecture Study Note (1)

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

Aggregationo 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 objectso 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

Page 16: Lecture Study Note (1)

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 it’s appropriate use

New class inherited from another class called Base classo “General” class from which others derive

Derived classo New class

o Automatically has base class’s:

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 Classo Refers to derived class

Ancestor classo Class that’s a parent of a parent

Descendant classo Class that’s 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

Page 17: Lecture Study Note (1)

17

The Protected: Qualifier New classification of class members Allows access “by name” in derived class but nowhere else In class it’s 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 Function’s name

o Sequence of types in parameter list

Including order, number, types Signature does NOT include:

o Return type

o Const keyword

o &

Page 18: Lecture Study Note (1)

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 variableso Any data they “point” to

o Base class destructor handles inherited data automatically

Destructor Calling Order Consider:

Class B derives from class AClass C derives from class BA B C

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

Page 19: Lecture Study Note (1)

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 datao 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 classo 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:

Page 20: Lecture Study Note (1)

20

o Can be accessed “by name” in derived class member functions

Overloaded assignment operator not inheritedo Can be invoked from derived class

Constructors are not inheritedo Are invoked from derived class’s 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

Virtualo Existing in essence though not in fact

Virtual Functiono Can be used before it’s 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:

Page 21: Lecture Study Note (1)

21

Rectangle r;Circle c;r.draw(); //Calls Rectangle class’s drawc.draw(); //Calls Circle class’s 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 classderived 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() won’t work for triangles

• Want inherited function center() to use function Triangle::draw() NOT function Figure::draw()

– But class Triangle wasn’t even WRITTEN whenFigure::center() was! Doesn’t know "triangles"!

Figures Example: Virtual Tells compiler:

o “Don’t know how function is implemented, wait until used in program”

o “Then get implementation from object instance”

Called late binding or dynamic bindingo Virtual functions implement late binding

Virtual Functions: Another Example

• Bigger example best to demonstrate

Page 22: Lecture Study Note (1)

22

• Record-keeping program for automotive parts store– Track sales– Don’t 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 Definitionclass 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{

Page 23: Lecture Study Note (1)

23

return (bill() – other.bill());}• 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 won’t automatically use Sale’s 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;};

DiscountSale’s Implementation of bill()• double DiscountSale::bill() const{double fraction = discount/100;return (1 – fraction)*getPrice();}

Page 24: Lecture Study Note (1)

24

• Qualifier "virtual" does not go in actual function definition– "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• DiscountSale’s member function bill() implemented differently than Sale’s

– 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

Page 25: Lecture Study Note (1)

25

• Very important

Overriding Virtual function definition changed in a derived class

o We say it’s been overridden

Similar to redefinedo 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 it’s members

o Its purpose solely for other to derive from

Recall class figureo All figures are objects of derived class

Rectangles, circles, triangles, etco 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 classo Can only be used as base class

o No objects can ever be created from it

Since it doesn’t have complete definitions of all its members

Page 26: Lecture Study Note (1)

26

If derived class fails to define all pure virtual functions:o It’s 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 arepublic!

– 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";

Page 27: Lecture Study Note (1)

27

vpet = vdog;– 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!• Can’t 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" it’s 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

Page 28: Lecture Study Note (1)

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 it’s 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 Don’t need to know how to use it

o Principle of information hiding

Virtual function tableo 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 pointero Points to virtual function table

Page 29: Lecture Study Note (1)

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 definitiono 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 objectso Base class members are lost; slicing problem

Pointer assignments and dynamic objectso Allow “fix” to slicing problem

Make all destructors virtualo 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

Page 30: Lecture Study Note (1)

30

Function Templates vs. Overloading Could overload function for chars:

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 what’s 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 typeo 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

Page 31: Lecture Study Note (1)

31

Function Template Definition swapValues() function template is actually a large “collection” of definitions

o A definition for each possible type

Compiler only generates definitions when requiredo But it’s “as if” you’d 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 Needn’t 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

Page 32: Lecture Study Note (1)

32

Compiler Complications Function declarations and definitions

o Typically we have them separate

o For templates not supported on most compilers!

Safest to place template function definition in file where invokedo Many compilers require it appears 1st

o Often we #include all template definitions

More Compiler Complications Check your compiler’s 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 it’s 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

Page 33: Lecture Study Note (1)

33

o Using actual data types

Completely debug “ordinary” function Then convert to template

o Replace type names with type parameter as needed

Advantageso 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 functiono Cannot use type for which assignment operator isn’t 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 Definitiontemplate<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;

Page 34: Lecture Study Note (1)

34

};

Template Class Pair Memberstemplate<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);

Page 35: Lecture Study Note (1)

35

o The type (int) is supplied to be used for T in defining this class type

parameterso It “happens” to be call-by-reference here

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

Page 36: Lecture Study Note (1)

36

Very common to have friends of template classeso Especially for operator overloads (as we’ve seen)

Predefined Template Classes Recall vector class

o Template class

Another: basic_string template classo Deals with strings of “any-type” elements:

Basic_string<char> works for char’s“” “” <double> works for doubes“” “” <YourClass> works for class objects

Basic_String Template Class

Already used it; Recall “string”o It’s 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 templateso 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

Page 37: Lecture Study Note (1)

37

Exception Handling Basics Meant to be used sparingly

o In “involved” situations

Toy Example Imagine: people rarely run of milk:

cout << "Enter number of donuts:";cin >> donuts;cout << "Enter number of glasses of milk:";cin >> milkdpg = 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

Page 38: Lecture Study Note (1)

38

Toy Example try-catch Try block

o Handles “normal” situation

Catch blocko 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{

Page 39: Lecture Study Note (1)

39

Code_to_tryIf (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-blocko Executing catch block called “catching the exception”

Exceptions must be “handled” in some catch block

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

catcho 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 it’s used

Exception Class for Toy Example Consider

Class NoMilk{public:

Page 40: Lecture Study Note (1)

40

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 throwno Each catch block only catches “one type”

o Typical to place many catch-blocks after each try-block

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 function’s try-catch-blocko Place call inside try-block

o Handle in catch-block after try-block

Page 41: Lecture Study Note (1)

41

Exception Specification Functions that don’t catch exceptions

o Should “warn” users that it could throw

o But it won’t 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)

o Function unexpected() automatically called

Default behaviour is to terminate Can modify behavior

Same result if no catch-block found

Throw List Summaryvoid 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 it’s also object

of class B

Page 42: Lecture Study Note (1)

42

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: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 functionso 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;

Page 43: Lecture Study Note (1)

43

Throws same exception againo 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 functionso 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

o Unrestricted flow of control

Lecture 10

Iterators Recall: generalization of a pointer

o Typically even implemented with pointer

Abstraction of iteratorso Designed to hide details of implementation

o Provide uniform interface across different container classes

Each container class has “own” iterator typeo 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 classo Has all above overloads

o Also has members begin() and end()

Page 44: Lecture Study Note (1)

44

c.begin(); //Returns iterator for 1st item in cc.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 they’re all used similarly

Vector Iterator Example//Program to demonstrate STL iterators.2 #include <iostream>3 #include <vector>4 using std::cout;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

Page 45: Lecture Study Note (1)

45

Here is what is in the container:1 2 3 4Setting entries to 0:Container now contains:0 0 0 0

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;

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

Page 46: Lecture Study Note (1)

46

Bidirectional and Random-Access Iterator Use

Iterator Classifications Forward iterators:

o ++ works on iterator

Bidirectional iteratorso Both ++ and -- work on iterator

Random-access iteratorso ++, --, and random access all work with iterator

Constant and Mutable Iterators Dereferencing operator’s 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

Page 47: Lecture Study Note (1)

47

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;

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

Page 48: Lecture Study Note (1)

48

Each is template class with parameter for particular data type to be storedo E.g., List of ints, double or myClass types

Each has own iteratorso 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 containero 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;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( );

Page 49: Lecture Study Note (1)

49

iter++)22 cout << *iter << " ";23 cout << endl;24 return 0;25 }

SAMPLE DIALOGUEList contains:1 2 3Setting 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 stack’s 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 containerpriority_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

Associative Containers Associative container: simple database Store data

o Each data item has key

Example:data: employee’s record as structkey: employee’s SSN

o Items retrieved based on key

Page 50: Lecture Study Note (1)

50

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 Class1 //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’);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': ";

Page 51: Lecture Study Note (1)

51

22 if (s.find('C')==s.end( ))23 cout << " no " << endl;24 else26 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 else36 cout << " yes " << endl;37 return 0;38 }SAMPLE DIALOGUEThe set contains:A B C DSet contains 'C': yesRemoving C.A B DSet 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;

Can use [] notation to access the mapo For both storage and retrieval

Stores in sorted order, like seto Second value can have no ordering impact

Program Using the Map Template1 //Program to demonstrate use of the map template class.2 #include <iostream>3 #include <map>4 #include <string>5 using std::cout;

Page 52: Lecture Study Note (1)

52

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 casethe output will be listed alphabetically by planet.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

Page 53: Lecture Study Note (1)

53

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 STL’s 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 valueso Argument is input size:

T(10), T(10,000),…. Function T is called “running time”

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 Doesn’t matter how “fast” computers are

o Can’t count “time”

Page 54: Lecture Study Note (1)

54

o Instead count “operations”

Counting Exampleint I = 0;bool found = false;while (( I < N) && !found)if (a[I] == target)found = true;elseI++;

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 systemso We say code runs in time O(6N+5)

o But typically only consider “highest term”

Term with highest exponento 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!

Page 55: Lecture Study Note (1)

55

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

Nonmodifying Sequence Algorithms Template functions operating on containers

o No modification of container contents

Generic find functiono Typical example

o Can be used with any STL sequence container class

Generic Find Function Example1 //Program to demonstrate use of the generic find function.

Page 56: Lecture Study Note (1)

56

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 yourfirst 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++)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

Page 57: Lecture Study Note (1)

57

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 sortedo 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 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

Page 58: Lecture Study Note (1)

58

Vasa Case Study Table

Page 59: Lecture Study Note (1)

59

Sample QuestionsQ3: What is three-tier architecture?a) Presentation, Object and Datab) Interface, Middleware and Informationc) Presentation, Class and Knowledged) None of the aboveANS: 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 aboveANS: d

Sample QuestionThe ability to reuse objects already defined, perhaps for a different purpose, with modification appropriate to the new purpose, is referred to as:a) Information hidingb) Inheritancec) Redefinitiond) OverloadingAnswer: 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 relationshipb) A fraternal relationshipc) An is-a relationshipd) There is no relationship here.Answer: c)

Page 60: Lecture Study Note (1)

60

Sample MC Question 3 (1.5%)Virtual functions are implemented with a table look up that is done at run time.a) Trueb) Falsec) False if you turn on the debuggerd) None of the aboveAnswer: 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) 1c) 2d) As many as are neededAnswer: 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 1‐3:  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 defined by the recurrence relation Fn = Fn‐1 + 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____ } 

Page 61: Lecture Study Note (1)

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? (a) O(1) 

Page 62: Lecture Study Note (1)

62

(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 

Page 63: Lecture Study Note (1)

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 same element. (d) All of the above ANSWER: d 

Question 9.

Page 64: Lecture Study Note (1)

64

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:  setPayment 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 Marks)  Next define a class named CashPayment that is derived from Payment.  This class should redefine the paymentDetails function to indicate that the payment is in cash "The cash payment amount is ".  Include appropriate constructor(s). (4 Marks)  Define a class named CreditCardPayment that is derived from Payment. This class should contain member  variables  for  the  name  on  the  card,  expiration  date,  and  credit  card  number.  Include appropriate constructor(s). Finally, redefine the paymentDetails function to include all credit card information in the printout. (8 Marks) Payment, CashPayment, CreditCardPayment Suggestion Answer: //payment.cpp // //This program introduces inheritance through a problem of // creating two types of Payments, Cash and Credit. The // PaymentDetails method outputs in English a sentence that describes // the payment.

Page 65: Lecture Study Note (1)

65

#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 // ====================== void Payment::setPayment(float amt) { amount = amt; }

Page 66: Lecture Study Note (1)

66

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() { } CashPayment::CashPayment(float amt) : Payment(amt) { } // ====================== // paymentDetails

Page 67: Lecture Study Note (1)

67

// 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 = ""; } CreditCardPayment::CreditCardPayment(float amt, string name, string expiration, string creditcard) : Payment(amt) { this->name = name;

Page 68: Lecture Study Note (1)

68

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 for the three classes: Payment, CashPayment, and CreditCardPayment. (5 Marks)  Turn the base class’s member function named paymentDetails into a virtual function and rewrite the C++  codes  you built  in Question. Briefly describe the differences between this dynamic binding approach and the “redefine” approach in Question 13. (10 Marks)  Suggestion Answer: Study the lecture notes on dynamic binding and we will discuss it at the Revision Class on April 22, 2014 (Tuesday). 

Page 69: Lecture Study Note (1)

69

Exception Handling Example

Sample DiagramsDraw 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 mayappear multiple times in the diagram.]

Page 70: Lecture Study Note (1)

70

Description of operations of the radioThe radio has three touch-sensitive buttons marked:OFF, SOUND, LIGHT. It also has a decorative light and aloudspeaker. At the start, the radio produces no lightand no sound. When the button SOUND is pressed, theloudspeaker is turned on (but the light status remainsunchanged). When the button LIGHT is pressed, thelight is turned on (but the loudspeaker status remainsunchanged). When the button OFF is pressed, the radioproduces no light and no sound.

Page 71: Lecture Study Note (1)

71

Page 72: Lecture Study Note (1)

72

Page 73: Lecture Study Note (1)

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 assignmentAccountType 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 options should not be allowed by the compiler. Here we just make sure we have a switch case for each AccountType optoin.

Page 74: Lecture Study Note (1)

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 have any buffer overflow problems. For example if the user inputs the address we must allocate enough space for the input and also validate that the size of the input has not been exceeded.