1 Chapter 6 Object-Oriented Software Development.

Slides:



Advertisements
Similar presentations
Chapter 3 ADT Unsorted List. List Definitions Linear relationship Each element except the first has a unique predecessor, and Each element except the.
Advertisements

1 Data Structures CSCI 132, Spring 2014 Lecture 8 Implementing Queues.
What is a Queue? n Logical (or ADT) level: A queue is an ordered group of homogeneous items (elements), in which new elements are added at one end (the.
What is a Queue? A queue is a FIFO “first in, first out” structure.
Chapter 5 ADTs Stack and Queue. 2 Goals Describe a stack and its operations at a logical level Demonstrate the effect of stack operations using a particular.
1 A full binary tree A full binary tree is a binary tree in which all the leaves are on the same level and every non leaf node has two children. SHAPE.
Inheritance CS 308 – Data Structures “the mechanism by which one class acquires the properties of another class” the properties of another class”
1 class Rectangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept.
Inheritance and Composition (aka containment) Textbook Chapter –
1 C++ Plus Data Structures Nell Dale Chapter 1 Software Engineering Principles.
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 expanded by J. Goetz Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
5 Linked Structures. 2 Definition of Stack Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 Fall Chapter 4 ADT Sorted List. 2 Goals Describe the Abstract Data Type Sorted List from three perspectives Implement the following Sorted List.
1 Abstract Data Type (ADT) a data type whose properties (domain and operations) are specified (what) independently of any particular implementation (how)
1 Review: Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM PROGRAM FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT.
Lecture 6: Polymorphism - The fourth pillar of OOP - 1.
1 Chapter 14-1 Object- Oriented Software Development Dale/Weems.
1 Chapter 14-2 Object- Oriented Software Development Dale/Weems.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
CMSC 202 Inheritance.
1 Chapter 14 Object-Oriented Software Development.
Chapter 3 ADT Unsorted List. Lecture 7 List Definitions Linear relationship Each element except the first has a unique predecessor, and Each element.
1 Chapter 14 Object- Oriented Software Development Dale/Weems.
1 Chapter 14 Object-Oriented Software Development Dale/Weems/Headington.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
1 Chapter 14 Object-Oriented Software Development Dale/Weems.
3 ADT Unsorted List. List Definitions Linear relationship Each element except the first has a unique predecessor, and each element except the last has.
Inheritance CS 302 – Data Structures Section 2.4 (pp ) and Section 6.7.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Chapter 5 ADTs Stack and Queue. Stacks of Coins and Bills.
1 Lecture 6: Polymorphism - The fourth pillar of OOP -
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition.
1 Overview of Object-Oriented Software Design and Java Programming Putting the Pieces Together!
1 Final Exam Tues 3/16/10 (2-3:50) (Same classroom) Old Textbook - Chapters 11-16, 18 Focus is on 15, 16 and 18 Final Exam Tues 3/16/10 (2-3:50) (Same.
10/18/2011ecs40 fall Software Development & Object- Oriented Programming ecs40 Fall 2012: Software Development & Object- Oriented Programming #02:
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
1 C++ Plus Data Structures Nell Dale Chapter 5 Linked Structures Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
1 Another way to define a class Inheritance..!!. 2 Why Inheritance ? Inheritance is a mechanism for building class types from existing class types defining.
CSI 1340 Introduction to Computer Science II Chapter 6 Lists Plus.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
Chapter 12 Classes and Abstraction
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Inheritance Concept Polygon Rectangle Triangle class Rectangle{
Inheritance Saras M. Srivastava LEARN BY EXAMPLES PGT – Comp. Sc.
Inheritance CMSC 202, Version 4/02.
C++ Plus Data Structures
Polymorphism.
Review: Two Programming Paradigms
Chapter Structured Types, Data Abstraction and Classes
Chapter 5 ADTs Stack and Queue.
Introduction to Structured Data Types and Classes
C++ Plus Data Structures
Introduction to Classes
Programming Techniques Course
Chapter 14 Object-Oriented Software Development
C++ Plus Data Structures
CSI 1340 Introduction to Computer Science II
Data Structures and Algorithms Memory allocation and Dynamic Array
Another way to define a class
Lecture 6: Polymorphism
Presentation transcript:

1 Chapter 6 Object-Oriented Software Development

2 Chapter 6 Topics l Structured Programming vs. Object-Oriented Programming Using Inheritance to Create a New C++ class Type Using Composition (Containment) to Create a New C++ class Type l Static vs. Dynamic Binding of Operations to Objects l Virtual Member Functions

3 Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM PROGRAM FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT Operations Data

4 Object-Oriented Programming Language Features 1. Data abstraction 2. Inheritance of properties 3. Dynamic binding of operations to objects

5 OOP Terms C++ Equivalents ObjectClass object or class instance Instance variablePrivate data member MethodPublic member function Message passingFunction call ( to a public member function )

6 What is an object? OBJECT Operations Data set of methods (public member functions) internal state (values of private data members)

7 Inheritance Hierarchy Among Vehicles vehicle wheeled vehicleboat bicyclecar four-door two-door Every car is a wheeled vehicle.

8 Inheritance l is a mechanism by which one class acquires (inherits) the properties (both data and operations) of another class l the class being inherited from is the Base Class (Superclass) l the class that inherits is the Derived Class (Subclass) l the derived class is then specialized by adding properties specific to it

9 class Time Specification // SPECIFICATION FILE( time.h ) class Time { public : void Set ( int hours, int minutes, int seconds ) ; void Increment ( ) ; void Write ( ) const ; Time ( int initHrs, int initMins, int initSecs ) ; // constructor Time ( ) ; // default constructor private : int hrs ; int mins ; int secs ; } ;

10 Class Interface Diagram Private data: hrs mins secs Set Increment Write Time Time class

11 Using Inheritance to Add Features // SPECIFICATION FILE ( exttime.h) #include “time.h” enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT, PDT } ; class ExtTime : public Time // Time is the base class { public : void Set ( int hours, int minutes, int seconds, ZoneType timeZone ) ; void Write ( ) const ; ExtTime ( int initHrs, int initMins, int initSecs, ZoneType initZone ) ; // constructor ExtTime ( ) ; // default constructor private : ZoneType zone ; // added data member } ;

12 class ExtTime: public Time l says class Time is a public base class of the derived class ExtTime l as a result, all public members of Time (except constructors) are also public members of ExtTime l in this example, new constructors are provided, new data member zone is added, and member functions Set and Write are overridden

13 Class Interface Diagram Private data: hrs mins secs ExtTime class Set Increment Write Time Set Increment Write ExtTime Private data: zone

14 Client Code Using ExtTime #include “exttime.h”. ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; // default constructor called thatTime.Write( ) ; // outputs 00:00:00 EST cout << endl ; thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDT cout << endl ; thisTime.Increment ( ) ; thisTime.Write ( ) ; // outputs 08:35:02 PST cout << endl ;

15 Constructor Rules for Derived Classes l at run time, the base class constructor is implicitly called first, before the body of the derived class’s constructor executes l if the base class constructor requires parameters, they must be passed by the derived class’s constructor

16 Implementation of ExtTime Default Constructor ExtTime :: ExtTime ( ) // Default Constructor // Postcondition: // hrs == 0 && mins == 0 && secs == 0 // (via an implicit call to base class default constructor ) // && zone == EST { zone = EST ; }

17 Implementation of Another ExtTime Class Constructor ExtTime :: ExtTime ( /* in */ int initHrs, /* in */ int initMins, /* in */ int initSecs, /* in */ ZoneType initZone ) : Time (initHrs, initMins, initSecs) // constructor initializer // Precondition: 0 <= initHrs <= 23 && 0 <= initMins <= 59 // 0 <= initSecs <= 59 && initZone is assigned // Postcondition: //zone == initZone && Time set by base class constructor { zone = initZone ; }

18 Implementation of ExtTime::Set function void ExtTime :: Set ( /* in */ int hours, /* in */ int minutes, /* in */ int seconds, /* in */ ZoneType time Zone ) // Precondition: 0 <= hours <= 23 && 0 <= minutes <= 59 // 0 <= seconds <= 59 && timeZone is assigned // Postcondition: //zone == timeZone && Time set by base class function { Time :: Set (hours, minutes, seconds); zone = timeZone ; }

19 Implementation of ExtTime::Write Function void ExtTime :: Write ( ) const // Postcondition: //Time has been output in form HH:MM:SS ZZZ // where ZZZ is the time zone abbreviation { static string zoneString[8] = { “EST”, CST”, MST”, “PST”, “EDT”, “CDT”, “MDT”, “PDT” } ; Time :: Write ( ) ; cout << ‘ ‘ << zoneString [zone] ; }

20 often several program files use the same header file containing typedef statements, constants, or class type declarations--but, it is a compile-time error to define the same identifier twice l this preprocessor directive syntax is used to avoid the compilation error that would otherwise occur from multiple uses of #include for the same header file #ifndef Preprocessor_Identifier #define Preprocessor_Identifier. #endif Avoiding Multiple Inclusion of Header Files

21 Composition (or Containment) l is a mechanism by which the internal data (the state) of one class includes an object of another class

22 A TimeCard object has a Time object #include “time.h” class TimeCard { public: void Punch ( /* in */ int hours, /* in */ int minutes, /* in */ int seconds ) ; void Print ( ) const ; TimeCard ( /* in */ long idNum, /* in */ int initHrs, /* in */ int initMins, /* in */ int initSecs ) ; TimeCard ( ) ; private: long id ; Time timeStamp ; } ;

23 TimeCard Class TimeCard has a Time object Private data: hrs mins secs Punch Private data: id timeStamp Increment Set Print. TimeCard Write.

24 Implementation of TimeCard Class Constructor TimeCard :: TimeCard ( /* in */ long idNum, /* in */ int initHrs, /* in */ int initMins, /* in */ int initSecs ) : timeStamp (initHrs, initMins, initSecs) // constructor initializer // Precondition: 0 <= initHrs <= 23 && 0 <= initMins <= 59 // 0 <= initSecs <= 59 && initNum is assigned // Postcondition: //id == idNum && timeStamp set by its constructor { id = idNum ; }

25 Order in Which Constructors are Executed Given a class X, l if X is a derived class its base class constructor is executed first l next, constructors for member objects (if any) are executed (using their own default constructors if none is specified) l finally, the body of X’s constructor is executed

26 In C++... When the type of a formal parameter is a parent class, the argument used can be: the same type as the formal parameter, or, any descendant class type.

27 Static Binding l is the compile-time determination of which function to call for a particular object based on the type of the formal parameter l when pass-by-value is used, static binding occurs

28 Static Binding Is Based on Formal Parameter Type void Print ( /* in */ Time someTime ) { cout << “Time is “ ; someTime.Write ( ) ; cout << endl ; } CLIENT CODE OUTPUT Time startTime ( 8, 30, 0 ) ;Time is 08:30:00 ExtTime endTime (10, 45, 0, CST) ;Time is 10:45:00 Print ( startTime ) ; Print ( endTime ) ;

29 Dynamic Binding l is the run-time determination of which function to call for a particular object of a descendant class based on the type of the argument l declaring a member function to be virtual instructs the compiler to generate code that guarantees dynamic binding

30 Virtual Member Function // SPECIFICATION FILE ( time.h ) class TimeType { public :... virtual void Write ( ) const ; // for dynamic binding... private : int hrs ; int mins ; int secs ; } ;

31 Dynamic binding requires pass-by-reference void Print ( /* in */ Time & someTime ) { cout << “Time is “ ; someTime.Write ( ) ; cout << endl ; } CLIENT CODE OUTPUT Time startTime ( 8, 30, 0 ) ; Time is 08:30:00 ExtTime endTime (10, 45, 0, CST) ; Time is 10:45:00 CST Print ( startTime ) ; Print ( endTime ) ;

32 Using virtual functions in C++ l dynamic binding requires pass-by-reference when passing a class object to a function l in the declaration for a virtual function, the word virtual appears only in the base class l if a base class declares a virtual function, it must implement that function, even if the body is empty l a derived class is not required to re-implement a virtual function. If it does not, the base class version is used

33 Private data value ComparedTo Print Initialize class ItemType An example: ItemType Class Interface Diagram

34 Sorted list contains an array of ItemType Is this containment or inheritance? SortedType class IsFull LengthIs ResetList DeleteItem InsertItem MakeEmpty RetrieveItem Private data: length info [ 0 ] [ 1 ] [ 2 ] [MAX_ITEMS-1] currentPos GetNextItem

35 class QueType QueType ~QueType Enqueue Dequeue. Private Data: qFront qRear ‘C’‘Z’ ‘T’

36 // DYNAMICALLY LINKED IMPLEMENTATION OF QUEUE #include "ItemType.h" // for ItemType template class QueType { public: QueType( ); // CONSTRUCTOR ~QueType( ) ;// DESTRUCTOR bool IsEmpty( ) const; bool IsFull( ) const; void Enqueue( ItemType item ); void Dequeue( ItemType& item ); void MakeEmpty( ); private: NodeType * qFront; NodeType * qRear; }; 36

37 // DERIVED CLASS CountedQue FROM BASE CLASS QueType template class CountedQue : public QueType { public: CountedQue( ); void Enqueue( ItemType newItem ); void Dequeue( ItemType& item ); int LengthIs( ) const; // Returns number of items on the counted queue. private: int length; }; SAYS ALL PUBLIC MEMBERS OF QueType CAN BE INVOKED FOR OBJECTS OF TYPE CountedQue

38 class CountedQue QueType ~QueType Enqueue Dequeue. Private Data: qFront qRear ‘C’‘Z’ ‘T’ CountedQue LengthIs Enqueue Dequeue. Private Data: length 3

39 // Member function definitions for class CountedQue template CountedQue ::CountedQue( ) : QueType ( ) { length = 0 ; } template int CountedQue ::LengthIs( ) const { return length ; }

40 template void CountedQue ::Enqueue( ItemType newItem ) // Adds newItem to the rear of the queue. // Increments length. { length++; QueType ::Enqueue( newItem ); } template void CountedQue ::Dequeue(ItemType& item ) // Removes item from the rear of the queue. // Decrements length. { length--; QueType ::Dequeue( item ); } 40

41 Example of using Protected #include class DynBase {protected: int *barr; // pointer to base class dynamic array public: DynBase () { cout << "Allocate 3 element DynBase array" << endl; barr = new int[3]; }

42 ~DynBase () // not a virtual destructor { cout << "Delete 3 element DynBase array" << endl; delete [] barr; } };

43 class DynDerived: public DynBase { private: int *darr; // pointer to derived class dynamic array public: DynDerived () : DynBase() { cout << "Allocate 4 element DynDerived array" << endl; darr = new int[4]; }

44 ~DynDerived () { cout << "Delete 4 element DynDerived array” << endl; delete [] darr; } };

45 int main() { DynBase *p = new DynDerived; delete p; return 0; }

46 /* Run: (DynBase destructor is not virtual): Allocate 3 element DynBase array Allocate 4 element DynDerived array Delete 3 element DynBase array */

47 #include class DynBase {protected: int *barr; // pointer to base class dynamic array public: DynBase () { cout << "Allocate 3 element DynBase array" << endl; barr = new int[3]; }

48 virtual ~DynBase () // virtual destructor { cout << "Delete 3 element DynBase array" << endl; delete [] barr; } };

49 class DynDerived: public DynBase { private: int *darr; // pointer to derived class dynamic array public: DynDerived () : DynBase() { cout << "Allocate 4 element DynDerived array" << endl; darr = new int[4]; }

50 ~DynDerived () { cout << "Delete 4 element DynDerived array" << endl; delete [] darr; } };

51 int main() { DynBase *p = new DynDerived; delete p; return 0; }

52 /* Run: (DynBase destructor is virtual): Allocate 3 element DynBase array Allocate 4 element DynDerived array Delete 4 element DynDerived array Delete 3 element DynBase array */