Intro Computer Science II
Intro Computer Science II COSC 1320
Popular in Course
Popular in Chemistry
This 73 page Class Notes was uploaded by Lowell Harris on Saturday September 19, 2015. The Class Notes belongs to COSC 1320 at University of Houston taught by Staff in Fall. Since its upload, it has received 47 views. For similar materials see /class/208181/cosc-1320-university-of-houston in Chemistry at University of Houston.
Reviews for Intro Computer Science II
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 09/19/15
3 Classes Construction amp Destruction Constructors Object Initialization Guarantees that an object is in a valid state upon creation Constructor is automatically called when an object is created 0 Constructor has the same name as the Class 0 No return value Example of Writing a Constructor class Switch In the Switchh le public SwitchO Declaration of a Constructor for the Switch class void turnOn private bool position In the Switchcpp le SwitchSwitch Implementation of the Constructor position true Writing Constructors class Date Dateint rmonth int rday int ryear Say this is only constructor for Date Date xmas12 25 1996 samsdob010182 Date bobsdob Error can t create without more info Several Ways to Initialize an Object Five Constructors for Date Class Dateint rm int rd int ry month day year Date int int month day This year Date int month This year amp day DateO39 Initialize to today Dateconst char39 In the form June 10 1996 061096 etc Five Ways to Create a Date Object Date dobl l 1996 Calls Date int int int Date christmas12 25 christmas 96 Date newyearsdayl39 Jan l 1996 Date today Todays Date Date july4 July 4 1996 How about Date vacationstartdate today 7 Initializing one Object Using Another String str2 strl BitWisecopy String strl Hello astrin f00Str1 g strl get fooconst Stringamp astring Strz Str 5 String str2 astring5 str2set Surprise Deep vs Shallow Copy Copy Constructor Ensures Proper Initialization of an Object 0 Of the form Xconst Xamp StringStringconst Stringamp otherobj str new char strlenotherobjstr l strcpystr otherobjstr String str2 astring astrng str m2 g Invocation of a Copy Constructor 0 A Copy constructor is called Whenever a copy of an object is made 0 Is called when you create an object using another object of same type String strl Hello Does not call Copy constructor String str2 strl Calls copy construcytor 0 When you call a function with an argument by value void functionlString stringObj J A call to functionl results in a call to copy constructor Scope Automatic Variables amp Free Store 0 Scope of Objects in C Blocks functions 0 Automatic Variables Free Store Management new and delete Garbage Collection amp Destructor Cleaning Up when an Object is no longer needed Automating some routine final processing tasks class FileHandler filehandle int openconst charquotlt lename void close FileHandler close Destructor followed by the class name 0 No arguments No return value 0 Only one allowed per class class String String delete str Destructor for String Class called When Invocation of Destructor You do not call the destructor When ever an automatic variable goes out of scope destructor is String strObj Hello strObj goes out of scope here Its destructor is called ever an object on the heap is deleted by you String ptr new String Whats up delete ptr Destructor of String is called here Should I write a Destructor for my classquot 0 Generally you do not need a destructor if your class does not use pointers 0 If you class has pointer to another object or data that must be deleted when your object is destroyed then you must write a destructor 0 Later we will discuss Law Of Big Three struct amp class in C class amp struct both represent a class in C class provides private access rights by default struct provides public access rights by default classes are usually used to represent Classes struct used to represent data usually local Lab Work Details provided online 7 Operator Overloading Issues amp Mechanism Operator Overloading 0 Ease of Use amp Readability Rules 0 Overload only existing Operators 0 Can t change existing Operator de nitions 5 2 is 7 period 0 Operator precedence rules apply can t change Operator Overloading is merely a function a special functions though Examples using Complex class class Complex double rep imp public Complex double rp0 double ip0 set rp ip void set double rp double ip rep rp imp i13 void getdoubleamp rp doubleamp ip const rp rep ip i11113 Overloading the Operator as member function Adding two Complex numbers CAB Operator as a member function of Complex class Complex Complexoperatorconst Complexamp b const Complex temp temprep rep brep tempimp imp bimp return temp Overloading the Operator as global function Operator as a nonmember function of Complex class Complex operatorconst Complexamp a const Complexamp b double realpartofa realpartofb impartofa impartofb agetrealpart0fa impartofa b getrealpartofb impartofb Complex temp tempsetrealpartofarealpartofb impartofa impartofb return temp Mechanism involved in resolving a call to Operator Overloading C A B is equivalent to one of the following 0 C AoperatorB 7 The operator is associated with the left operand object 7 Expects to see a member function operator in class Complex which takes an object of type Complex as argument 0 C operatorA B 7 The operator is associated with neither object 7 Expects to see a global function operator which takes two objects of type Complex as argument Exerc15e on operator What are the possible ways to provide the following feature A is a Complex number C A 21 Add 21 double to the real part of A Exercise on operator Solution Provide Complex operatordouble val const as a member function of Complex Provide Complex operatorconst Complexamp a double val as a global function No need for any function if one of the following exists Complex Complex operatorconst Complexamp const Complex operatorconst Complexamp const Complexamp Since Complex double0 double0 can convert 21 to a Complex object Another Exercise on operator 0 What are the possible ways to provide the following feature A is a Complex number C 21 A Add 21 double to the real part of A Another Exercise on operator Solution 0 Recollect that 21 A is equivalent to one of the following 21operatorA operator21 A The first one is not possible since you can t redefine on double built in datatype Only option not considering type conversion provide Complex operatordouble val const Complexamp a Writing the 0perat0r for 21 A Complex operatordouble val const Complexamp A double realpartofa impartofa a getrealpartofa impartofa Function call Overhead Complex temp tempsetval realpartofa impartofa Function call Overhead return temp Eliminating Overhead that is what friends are for class Complex friend Complex operatordouble val const Complexamp a Complex operatordouble val const Complexamp A Complex temp temprep val arep Direct access to A s data and temp s tempimp aimp Direct access to A s data and temp s return temp Should I write a member function or a global friend function Pure objectoriented languages allow only member functions In C you may have a choice Some functions should be members operator Member do not introduce global names use these in absence of other reasons If implicit type conversion is desired for all operands of an operation use global functions If an operation modifies an operand rather than merely returning a result use member Cascading Operators DABC Where AB andC are Complex 0 DAB2l oD21A32 All that it takes is a proper return type in the operator overloaded function Lab Work Details provided online 6 Overloading Functions Inlz39m39ng etc Function Overloading Notational convenience for functions that perform the same task on objects of different types void print int a void print double b void print char c void print double a double b Overloaded functions must have different argument signature ie types andor ordering of arguments Name resolution Argument Matching Exact match with no or unavoidable conversion int to const int 0 Matching using integral promotions short to int 0 Matching using standard conversions int to double 0 Matching using userde ned conversions Lets match the calls to functions in the print example pIint1 p1intl2 37 pIint a printl 2 3 p1int12 print2 3 Constructors as Overloaded Functions class Complex double re double im public Complex double rep double imp Complex double rep imp is assumed 0 Complex const Complexamp obj Copy constructor 7 Complex 0162 81 Complex 0228 Complex 038 Complex c422 4 Complex 0504 Matching userdefined Conversion void print int a void print double b void print char c void print double a double b void print Complex a Lets match the calls to functions in the print example printl printl 2 37 print a printl 2 3 printl 2 printc3 Functions With Default Arguments Complex may be created with real and imaginary values or just with real value and an assumed 0 for the imaginary value Using overloading Complex double rep double imp Complex double rep Using default argument Complex double rep double imp 0 double powerdouble value int pwr2 Compute valuePWT if pwr not given compute value2 power3 3 27 power3 2 9 power3 9 Rule for Default Arguments 0 Default Arguments must be trailing void fooint a 0 int b int c 5 Error Example void computeint i l intj 2 int k 3 Effective values of arguments i j k in the following compute3 4 5 compute3 4 3 4 5 3 4 3 compute3 compute 323 123 Avoiding CStyle Macros Macros were used to help coding define MAX 1000 Problems with macros Textual replacement Preprocessor handles it 0 No precedenceType checks define SQUARE X X X SQUARE 2 3 Surprisell Encapsulation amp Performance inlining functions Function Call Overhead mywatchReset Calls a function to set seconds to 0 Functions may be inline d to avoid function call overhead Expands the function Where called Done by the compiler not preprocessor Checks for types and precedence rules are enforced Writing an Inline function 0 If function is defined Within the class it is considered inline 0 If function is defined outside the class specify inline explicitly class StopWatch long getSecondsO return seconds Inline since defined Within class inline void Reset Inline since speci ed void start Not inline Inline Functions Usage inline not an order request honored if function is small a few lines in size function is nonrecursive The code for the function should be available to the compiler for expanding on call This requires that the function be placed in the header file in case of class member inline functions not so desirable Suggestion worry about inlining functions when nearing release only advantage is performance Ellipsis Function with unspecified of arguments Provides exibility to pass variable of arguments void sortint number Sort variable of ints Sacrifice one of the best features of C strong type checking Implemented using valist structure 0 Don t even think about it 0 Only prudent use catching arbitrary exceptions Lab Work Details provided online 16 Standard Template Library ST L Standard Template L1brary Promotes Reuse 0 Saves time and effort 0 Better quality 0 part of ANSIISO C standard STL headers Defined in std namespace Headers are of form ltheadernamegt Without the h Containers 7 ltvectorgt lt1istgt ltdequegt ltqueuegt ltstackgt ltmapgt also multimap ltsetgt also multiset ltbitsetgt Iterators 7 ltiteratorgt Algorithms 7 lta1gorithmgt Strings 7 ltstringgt STL Containers Sequence Containers 7 vector insertdelete at back access any elem 7 deque insertdelete frontback access any elem Double ended queue deck 7 list doubly linked list insert delete any where Associative Containers 7 set lookup no duplicates 7 multiset lookup duplicates OK 7 map onetoone mapping no duplicates keybased lookup 7 multimap onetomany duplicates OK keybased lookup Container Adapters 7 stack Lastin rstout 7 queue Firstin rst out 7 priorityiqueue highest priority element is first out Container 39l ypes Firstclass Containers Sequence containers and Associative containers 0 Near Containers Almost containers arrays string bitset valarray Which one to choose 0 Standard Containers are interchangeable Each container is efficient for a certain usage Key based look up map List operations list Addremove elements at end deque stack queue Most common usage vector Common Operatlons and Members Common Member Types 7 valueitype allocatoritype sizeitype differenceitype iterator constiiterator reverseiiterator constireverseiiterator reference constireference for associative only keyitype mappeditype keyicompare Common Operations 7 Iterators begin end rbegin rend 7 Elements access front back not for list unchecked subscripting at 7 Stack and Queue operations 0 pushiback popiback list and deque only pushifront popifront 7 List Operations 0 insert erase clear Containers and Efficiency Sequence Adaptor Associative Source C Programming Language 3rd Ed Bjarne Stroupstrup Iterators Iterators used to point to an element of a container Container s begin returns an iterator pointing to the first element end returns an iterator pointing to the end next to last Use instance of iterator to point to element you want to modify Use instance of constiterator to point to element you do not want to modify gt iter refers to the pointed element iter advances the iterator to point to the next element Category of Iterators and Operations itr itr itri L input output 134 itr rvalue itr value m1 m2 itrl itr2 itrl itr2 forward it bidirectional itr i itr i random access itr i itrl lt itr2 notallapzmtmnslxs tzd itrl gt itr2 lterators Aid Generic Programming lterators decouple Algorithms from Containers Algorithms in STL Algorithms are used to manipulate containers 0 Loosely coupled to the containers 0 Works on lterators returned by Containers 0 Returns Iterator to elementresult Examples sort search delete find insert etc STL Algorithms Mutatingsequence algorithms 7 copy copyibackward fill fillin generate generatein iteriswap partition randomishuf e remove rem oveicopy removeicopyiif removeiif replace replaceicopy replaceicopyiif replaceiif reverse reverseicopy rotate rotateicopy stable liar tition swap swapiranges transform unique uniqueicopy Nonmutatingsequence algorithms 7 adjacentifind count countiif equal find forieach mismatch search searchin 0 Numerical algorithms 7 accumulate inner jroduct partialisum adjacentidifference Lab Work Details provided online 5 Classes Friends Containers amp Relationships Friends of a Class Provides Access to class Internals Breach of Encapsulation Discourage use of Friends Friend Functions amp Friend Classes class Paragraph friend int wordCountconst Paragraphamp thepara function WordCount is a friend of the class friend class Page class Page is a friend of the class ContainerCollection Classes The Object is actually a container Holds a collection of other objects class SetOfBoxes Boxquotlt ptrtoboxes void addBoxBoxamp abox Boxquotlt getBoxconst Stringamp boxlabel Boxquotlt removeBoxconst Stringamp boxlabel Generalized Template Classes may be used Relationships among Classes Association amp Aggregation Members of a Class Attributes 0 a data value held by an object 0 has no identity 0 pure data value Association Attributes Relationships between Classes Relationships among Classes 0 Association semantic relationship 0 has ownerpart Aggregation relationship Inheritance isa relationship Association 1 2 l Unlver51ty person Prov1des Education Examples of Association 0 A company employs several persons The company also owns several computers Each person may be assigned one computer for the person s use 0 A lab has several computers A student may reserve amp use a computer for a certain period of time Visibility of Classes Ways that one object may be made visible to another The supplier Object is 0 global to the client 0 a parameter to some operation of the client 0 a part of the client object 0 a locally declared object in the scope of the object diagram Aggregation has Wholepart Expresses Containment ownership bidirectional Navigability to Engine ltgt 9 SteeringWheel Ways to Contain Aggregation by Value Composite Aggregation Aggregation by Reference class Car Enginequotlt theEngine Q By Reference Transmission theTrans By Value Transmission I I Engine Containment By Value Vs By Reference ByValue BRtfaeme Geatim GeatedupaneatimofGntainer Cheated attahed detached destroyed Dzstrudim DesvxithGntainer DesvxithGntainerorearliermless detailed Eristenoe Mtyqnayr exist W133 W133 How would you express Person Owns Car Cardinality of Relationship The number of Objects expressed in the Relationship ln I Door I I Transmission I Multiple Relationships between Classes Employment Enrollment Example Object Diagram Em o lo ment Aggregation by Value Writing the Constructor class Elevator Elevator int bottom oor int top oor Needs service floor numbers to create an elevator class Building Elevators elevl elev2 Building int numof oors BuildingBuilding int numof oors elevl0 numof oors l elev2 l num of oors body of Building constructor Lab Work Details provided online 2 Classes Abstraction amp Encapsulation Objects amp Classes What is an Object Concept abstraction or thing with crisp boundary amp meaning for a problem Sam Laura myWatch frontWheel Objects amp Classes What is a Class 0 Group of Objects with similar properties attributes behavior relationships to other objects semantics Blueprints of Objects Person Watch Wheel Classes in C What does a class in C provide Abstraction Encapsulation 0 Ease of Use like builtintype An Example C Class Interface class Sw1tch Class Interface Sw1tchh file public Indicates that the members following this line may be accessed by any function void turnOn void turnOff bool getPositionO const This function does not change private Indicates member followmQWi E 3 WBg EE Wb hWCt member functions of this class bool position amplegnlaggclinnlgmaytgrton void Switch turnOn position true Accessing private object member void Switch turnOff position false bool Switch getPositionO const return position Creatlng amp Usmg Sw1tch Objects Object Creation 7 Switch obj Created on stack 7 Switch ptr new Switch Created on heap Object destruction 7 obj created on stack automatically destroyed 7 Object created on heap needs manual deletion delete ptr Calling member functions 7 objtumOn 7 ptrgttumOn Accessing member data 7 Only public members accessible 7 objp0siti0n true ERROR 7 ptrgtp0siti0n true ERROR Switch obj l Sw1tch Ob ects and Memory object on the stack Switch ptrl amp0bjl Switch ptr2 new the heap obj 1 obj 1 position ptr l ptr2 Access Control public Acces51ble by any function of any class private Accessible only by member functions of the same class Make most variables private Safe guard against change in variable name type of variable implementation of data structure like array to linked list closely monitor change in values Make most functions public Provides access to functionality defined by class Exhibits the prescribed behavior of class Helper or Utility Functions You may write functions that help you write other functions of a class These functions perform some tasks that are subtasks in other functions Example class SalesClerk public void completeSalesdouble amount updateRegisterO void processRefunddouble amount updateRegisterO private void updateRegisterO Does not make sense for user of class to call these functions Make these functions private const Functions A member function of a class may 7 read 7 modify any member variable of an object If I have an object I may call methods on the object Switch obj objturnOn bool currentState objgetPositionO What if I have const object an objectI can t change 7 Not be allowed to call methods that modify the obj ect 7 only const functions may be called const functions guarantee that state of object will not change when called nonconst object 7 const functions and nonconst functions may be called const Functions void SwitchturnOn Not const may modify members position true Modifying private object member bool SwitchgetPosition const if som eCondition position true ERROR can t modify member turnOnO ERROR can t call methods that may modify members Switch someOtherObject someOtherObjectturnOnO OK because it is not this object someOtherObjectposition false OK because it is not this object return position Coding Standard For Classes Interface defines what your class will do Implementation tells how you do it Interface given to others in readable form Implementation given to others in binary form Each function must explain its 7 purpose 7 requirement 7 promise 7 exception This convention illustrated in online examples Not shown on slides to save space A Date Class Interface class Date public void setint rmonth int rday int ryear Implementation provided with the interface Better not to You may validate rmonth rday and ryear before setting month rmonth day rday year ryear void getintamp rmonth intamp rday intamp ryear const private int month int day int year Data class Implementation void Date getintamp rmonth intamp rday intamp ryear const rmonth month rday day ryear year What is the memory organization of the Date Objects l A String Class Strings are mere array of characters in C Tedious to deal with String class Abstracts strings for easy use class String char str public String str 0 void setconst char val const char get const Implementatlon of get and set const char get const return str void String setconst char val if val 0 Pr0blem str new char strlenVal l strcpystr val Correct Implementatlon Clean char array before allocating new array void String setconst char val if str NULL delete str str 0 if val 0 str new char strlenVal l strcpystr val Lab Work Details provided online l l Inheritance Proper Inheritance Multiple Inheritance Public Inheritance should model isa B publicly inherits isa from A This means every object of type B is also an object of type A anything that is true of an object of A is also true of an object of B A represents a more general concept than B B represents a more specialized concept than A anywhere an object of A can be used an object of B can be used Requirements amp Promises of Functions Advertised Requirements PreCondition Advertised Promise Post Condition Expressing Requirement amp Promise Unfortunately in C use Disciplined and Consistent Comments Example void pushint elem class Stack PURPOSE pushes elem onto the top of stack REQUIRE numElemsO lt 10 PROMISE numElemsO int topO const PURPOSE returns the top element INITIAL E1 1 REQUIRE numElem s l 0 PROM SE 5111111177611 50 PROMISE nothing 0P0 6 em Substitutability Advertised Behavior of the Derived class is Substitutable for that of the Base class Substitutability Derived class Services Require no more and promise no less than the speci cations of the corresponding services in the base class Example int Base fnint X REQUIRE X is Odd int Derivedfn1nt X PROMISE Returns an even int REQUIRE X is int PROMISE Returns 8 Liskov Substitutability PrincipleLSP Any Derived class object must be substitutable Where ever a Base class object is used Without the need for the user to know the difference Inheritance appears Simple class Bird has beak Wings etc public virtual void yO Bird can y class Parrot public Bird Parrot is a bird public virtual void MimicO Can Repeat words Parrot mypet mypetMmicO my pet being a parrot can lLimic mypet y my pet isa bird can y Yes it just appears simple class Penguin public Bird Penguin is Bird This inheritance says that Penguins can y Result of Incorrect understanding from an imprecise language statement Birds can y does not mean all birds can y In general birds that have the ability to y can y Penguins may try to y but will fail Design class Bird has beak Wings etc public v01d PlayWithBird virtual void yO Bird can y Bird y abird class Penguin public Bird Penguin is a Bird abird yO OK if bird PUbh X happens to be virtual void yO error Penguins don t y Parrot Does not model Penguins can t y Eggsnlsfg Models Penguins may y but if they try it is an error Penguin Runtime error if an attempt is made to y not desirable Think about Substitutability Fails LSP Not all birds y Penguins can t Design class Bird has beak Wings etc No y function Birds have beak Wings don t want to say anything about ying here class FlyingBird public Bird A Bird that can y public virtual void yO class NonFlyingBird public Bird A Bird that can t y class Parrot public FlyingBird class Penguin public NonFlyingBird More examples on Inheritance 0 Does class Square inherit from class Rectangle 0 Does class Basket of Bananas inherit from Basket of Fruits Design should be based on Requirements and Requirements The best design depends on what the system is expected to do both now and in the future Multiple Inheritance An object is a kindof more than one type uaticBein swim A Terre strialBein walk A Ambiguous Functions in Multiple Inheritance TA sam samGoToClassO Student Teacher G T Cl G T Cl OStZdVSO 0T6ChaSSO TA has to overrlde the A A GoToClass function Sam Obj ect Student Data Teacher Data TA Data mywindow Object Duplication of Base Class Data in Multiple Inheritance class Window Represents a Window on the Computer class WindowWMenu public Window class WindowWScrollBar public Window class WindowWMenuAndScrollBar public WindowWMenu public WindowWScollBar WindowWMenuAndScrollBar mywindow Window Data WindowWMenu Data Window Data WindowWScrollBar Data WindowWMenuAndScrollBarDat Virtual Base Class class Window Represents a Window on the Computer class WindowWMenu public Virtual Window class WindowWScrollBar public Virtual Window class WindowWMenuAndScrollBar public Virtual Window public Virtual WindowWMenu public Virtual WindowWScollBar WindowWMenuAndScrollBar mywindow mywindow Window Data Object WindowWMenu Data WindowWScrollBar Data WindowWMenuAndS crollBarData Problems With Repetitive Calls to Functions in Multiple Inheritance 132333333th draw WindowWScrollBar drawO Window drawO WindOWW WindowWMenuAndScrollBardrawO Menu S crn I R ar WindowWMenu drawO draw draWO WindowWScrollBar draWO WindOWWMenu mywindowdrawo An d qcrn I R a Window draw will be called draw twice Lab Work Details provided online 17 I nput Output Mechanism Standard 10 F 1 16 10 Standard Input Output stdin cin stdout cout stderr cerr InputOutput Streams istream amp ostream InputOutput of Builtin Types Input Output of Userdefined Types The Stream Hierarchy Inheritance of istream and ostream from ios istream ostream Stream States class ios public int eof const end of file seen int fail const next operation will fail int bad const Stream corrupted int good const next operation might succeed Formatting Output class ios public int widthint w set field width int WidthO const return eld Width char fillchar set fill character char fill const return fill character int precisionint set oating point precision int precision const Manipulators setw setfill setprecision oct 0 he 0 dec 0 setbase Files and Streams ifstream amp ofstream ifstream ifobj filename ofstream ofobj filename ioszzout ioszznocreate open and close functions Flags nocreate 0 in 0 out noreplace g Lab Work Details provided online 15 Templates Need intamp maxintamp a intamp b oatamp maxfloatamp a oatamp b Timeamp maxTimeamp a Tim eamp b ifagtb ifagtb return a return a if a gt b else else return a return b return b 5155 return b Same process but different types Poor Reuse Templates Provides Generalized Implementation Template Function Implementation template ltclass Tgt Tamp maXTamp a Tamp b if a gt b return a else return b Template Function Instantiation Function Resolution when using Templates No implicit Type conversion Function Instantiated on Call maX55 44 Instantiate oat maX oat oat maX5 4 Instantiate int maXint int Does not convert int to oat maX a b Instantiate char maXchar char maX5 a Error no template for maXint char You may explicitly cast maX5 int a Templates Functions with Different Argument Types template ltclass T1 class T2 class T3gt void functionlTl a T2amp b T3quotlt ptr functionlobjole objofTZ ampobjofT3 Class Templates Express General Concepts that don t depend on a Specific Type template ltclass MEMBERgt class List public void addMEMBERamp obj bool containsconst MEMBERamp obj const void removeMEMBERamp obj MEMBERamp operatorint position const Writing a Template Member Function template ltclass MEMBERgt void ListltMEMBERgt addMEMBERamp obj template ltclass MEMBERgt MEMBERamp ListltMEMBERgt operator int position const Using a Class Template ListltPersongt personlist Person sam nancy bob personlistaddsam personlistaddnancy Person ptr amppersonlist0 ptr will point to sam since it is the rst element in the List ptr amppersonlistl ptr will point to nancy personlistcontainsbob Will return FALSE personlistremovesam Removes sam from the List ptr amppersonlist0 ptr will point to nancy An Iterator class Template template ltclass MEMBERgt class ListIterator ListltMEMBERgtamp thelist public ListIteratorListltMEMBERgtamp theilist bool operator const Returns a TRUE if end of List void operator Advance to next element in List MEMBER operatorgt0 Pass on the request to the MEMBER MEMBERS operator Return the current MEMBER in the List h Using an Iterator PrintNamesofPersonsconst ListltPersongtamp personlist ListIteratorltPersongt iterpersonlist while iter itergtPrintName PrintName is a member of thePerson class I could have also used iterPrintName iter Lab Work Details provided online 13 Polymorphism 39 Usage Mechanism The Effect of the Virtual keyword 0 Virtual specifier on a function indicates to a caller that an object of a derived class may use an alternate implementation 0 If a function is not Virtual it is always statically bound on references pointers and objects 0 If a function is Virtual it is dynamically bound on references and pointers not on objects Example of Binding class X public virtual void fl 0 void f2 virtual void 80 f10 f20 dynamic static X obj objflo Stilth objf2 static objf3 static X ptr ptrgtf1 namlc ptrgtf2 static ptrgtf3 dynamic Xamp ref re flO dynamic remo m reff3 dvnamic Virtual Tables amp vptr Ef cient Implementation of Polymorphism Example class Vehicle virtual void drive virtual void FillGas class Car public Vehicle virtual void drive virtual void RollWindowint class MotorBike public Vehicle virtual void drive Vehicle vl Car cl c2 MotorBike ml VTable for the Vehicle Example Vtable Vtable Virtual Destructor Employee eptrl new Employee void fnEmployee eptr Employee eptr2 new Manager delete eptr Should call fneptrl Employee or Manager 0 If a Class has a Virtual function it needs a Virtual destructor fneptr2 0 If you expect class to be used as Base class you must write a Virtual destructor Virtual Constructors Not available no Virtual constructors in C But Whats the Need Example class Car Engine engineptr 7 Car cl 02 Caramp operator7const Caramp Obj engineptr new Engine clSetEngineaTurboEng1ne engineptr objengineptr 02 cl Solution Prototype Pattern Car Car operatorconst Caramp obj engineptr objengineptrgtcreatenew engineptr objengineptr class Engine class TurboEngine Engine Virtual Engine createnewo Virtual Engine createnewo return new Engine return new TurboEngine Pure Virtual Functions Revisited A Pure Virtual Function is a Virtual Function with no implementation class Employee virtual void YearlyRevieWo 0 Pure Virtual Function Class with Pure Virtual Function is an Abstract Base class No instances of an ABC may be created An ABC is used to represent Abstract concepts and to inherit other classes from A class derived from an ABC must provide an implementation for the pure virtual function to be a concrete ie a non ABC class Caution Calling Virtual Functions in Constructors amp Destructors class Employee class Manager public Employee virtual void printO cout ltlt name virtual void printO Employeeconst char name Employeeprint cout ltlt Creating Employee cout ltlt level printO Which print called here Manager const char name int level virtual void reportO Employeename printO Which print called here cout ltlt Creating Manager PrintO Lab Work Details provided online
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'