10/18/2011ecs40 fall 20121 Software Development & Object- Oriented Programming ecs40 Fall 2012: Software Development & Object- Oriented Programming #02:

Slides:



Advertisements
Similar presentations
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
Advertisements

C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Classes: A Deeper Look Systems Programming.  constconst  const objects and const member functions   Composition   Friendship  this  this pointer.
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 –
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
 2006 Pearson Education, Inc. All rights reserved Templates.
1 Chapter 6 Object-Oriented Software Development.
Classes: A Deeper Look Systems Programming.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
Lecture 6: Polymorphism - The fourth pillar of OOP - 1.
1 Chapter 14-1 Object- Oriented Software Development Dale/Weems.
Review of C++ Programming Part II Sheng-Fang Huang.
1 Chapter 14-2 Object- Oriented Software Development Dale/Weems.
OOP Languages: Java vs C++
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 12: Adding Functionality to Your Classes.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
1 Chapter 14 Object-Oriented Software Development.
1 Chapter 14 Object- Oriented Software Development Dale/Weems.
Templates Zhen Jiang West Chester University
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Chapter 14 Object-Oriented Software Development Dale/Weems/Headington.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
1 Chapter 14 Object-Oriented Software Development Dale/Weems.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Chapter 10 Inheritance and Polymorphism
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
1 Lecture 6: Polymorphism - The fourth pillar of OOP -
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Classes, Interfaces and Packages
1 Another way to define a class Inheritance..!!. 2 Why Inheritance ? Inheritance is a mechanism for building class types from existing class types defining.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
 2006 Pearson Education, Inc. All rights reserved Templates.
Inheritance Concept Polygon Rectangle Triangle class Rectangle{
Inheritance Saras M. Srivastava LEARN BY EXAMPLES PGT – Comp. Sc.
Inheritance CMSC 202, Version 4/02.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Computer Science Department University of California, Davis
Chapter 14 Templates C++ How to Program, 8/e
Introduction to Custom Templates
Polymorphism.
Programming Techniques Course
Chapter 14 Object-Oriented Software Development
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Another way to define a class
Lecture 6: Polymorphism
Presentation transcript:

10/18/2011ecs40 fall Software Development & Object- Oriented Programming ecs40 Fall 2012: Software Development & Object- Oriented Programming #02: Chapters 11~14 Dr. S. Felix Wu Computer Science Department University of California, Davis

10/18/2011Object-Oriented setTime Time printUniversal printStandard int Constructor ecs40 fall 2012 “Separation of Interface and Implementation” Time.h Time.c main.c int 2

OO Paradigm in C++ l Operator Overloading l Inheritance l Polymorphism l Templates 10/18/2011ecs40 fall 20123

OO Paradigm in C++ l Operator Overloading (chapter 11) l Inheritance l Polymorphism l Templates 10/18/2011ecs40 fall 20124

© by Pearson Education, Inc. All Rights Reserved.

10/18/2011ecs40 fall strcpy, strcmp, strcat strtok, strncpy, strncmp, strlen strdup

© by Pearson Education, Inc. All Rights Reserved.

10/18/2011ecs40 fall Postfix i++ Prefix ++i

© by Pearson Education, Inc. All Rights Reserved.

Operator Overloading l = (assignment operator) + - * (binary arithmetic operators) += -= *= (compound assignment operators) == != (comparison operators) 10/18/2011ecs40 fall

10/18/2011ecs40 fall Binary – the first operand must be the object Overloading member Operators!

© by Pearson Education, Inc. All Rights Reserved.

10/18/2011ecs40 fall A couple questions here…

© by Pearson Education, Inc. All Rights Reserved.

10/18/2011ecs40 fall We will re-visit in Chapter 15!

10/18/2011ecs40 fall Rules for Operator Overloading Readability? “>” versus “strcmp” How would you find out whether a particular operator has been overloaded?

10/18/2011ecs40 fall l Sometimes it’s useful to determine the size of an array dynamically at execution time and then create the array. l C++ enables you to control the allocation and deallocation of memory in a program for objects and for arrays of any built-in or user-defined type. –Known as dynamic memory management; performed with new and delete. You can use the new operator to dynamically allocate (i.e., reserve) the exact amount of memory required to hold an object or array at execution time. l The object or array is created in the free store (also called the heap)—a region of memory assigned to each program for storing dynamically allocated objects. Once memory is allocated in the free store, you can access it via the pointer that operator new returns. You can return memory to the free store by using the delete operator to deallocate it.

10/18/2011ecs40 fall The new operator allocates storage of the proper size for an object of type Time, calls the default constructor to initialize the object and returns a pointer to the type specified to the right of the new operator (i.e., a Time * ). If new is unable to find sufficient space in memory for the object, it indicates that an error occurred by “throwing an exception.” –Chapter 16, Exception Handling, discusses how to deal with new failures.

10/18/2011ecs40 fall To destroy a dynamically allocated object, use the delete operator as follows: l delete ptr; This statement first calls the destructor for the object to which ptr points, then deallocates the memory associated with the object, returning the memory to the free store.

10/18/2011ecs40 fall

10/18/2011ecs40 fall l You can provide an initializer for a newly created fundamental-type variable, as in l double *ptr = new double( ); l The same syntax can be used to specify a comma-separated list of arguments to the constructor of an object.

10/18/2011ecs40 fall You can also use the new operator to allocate arrays dynamically. For example, a 10-element integer array can be allocated and assigned to gradesArray as follows: l int *gradesArray = new int[ 10 ]; l A dynamically allocated array’s size can be specified using any non-negative integral expression that can be evaluated at execution time. l Also, when allocating an array of objects dynamically, you cannot pass arguments to each object’s constructor—each object is initialized by its default constructor.

10/18/2011ecs40 fall l To deallocate a dynamically allocated array, use the statement l delete [] ptr; l If the pointer points to an array of objects, the statement first calls the destructor for every object in the array, then deallocates the memory. Using delete on a null pointer (i.e., a pointer with the value 0) has no effect.

10/18/2011ecs40 fall

© by Pearson Education, Inc. All Rights Reserved.

10/18/2011ecs40 fall Chapter 12: Inheritance Parent Child Base Derived Super Sub

10/18/2011ecs40 fall Chapter 12: Inheritance Parent Child Base Derived Super Sub Base Derived Inherit Is-A

10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall Chapter 12: Inheritance Parent Child Base Derived Super Sub CommissionEmployee BasePlusCommission Employee Inherit Is-A

10/18/2011ecs40 fall Chapter 12: Inheritance Parent Child Base Derived Super Sub CommissionEmployee BasePlusCommission Employee Inherit Is-A

Inheritance the Software Engineering perspective l Separating Interface from Implementation l Reusability –Interface, design or implementation l Generalization versus Specialization –Polymorphism (Chapter 13) 10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall Inheritance of Interface or Implementation?

10/18/2011 Base Constructor ecs40 fall

10/18/2011 Base Constructor ecs40 fall Derived Constructor

10/18/2011 Base Constructor ecs40 fall Derived Constructor Derived Constructor Interface

10/18/2011ecs40 fall

10/18/2011 Base Constructor ecs40 fall Derived Constructor

Inheriting “Partially” l Inherit an interface but NOT the implementation from the base class 10/18/2011ecs40 fall

10/18/2011 Base Constructor ecs40 fall Derived Constructor

10/18/2011 Base Constructor ecs40 fall Derived Constructor

10/18/2011 Base Constructor ecs40 fall Derived Constructor “protected” “private” “public”

10/18/2011ecs40 fall

10/18/2011ecs40 fall

Public/Protected/Private l class : public {…} l class : protected {…} l class : private {…} 10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall Chapter 12: Inheritance Parent Child Base Derived Super Sub CommissionEmployee BasePlusCommission Employee Inherit Is-A

Inheritance the Software Engineering perspective l Separating Interface from Implementation l Reusability –Interface, design or implementation l Generalization versus Specialization –Polymorphism (Chapter 13) 10/18/2011ecs40 fall

09/23/2011ecs150 Fall VM/MVS, DOS, Win95/98/ME/2000/XP, Freebsd/Linux, MacOS-10, Mach, Minix, PalmOS, uCOS, TinyOS, …

09/23/2011ecs150 Fall

10/07/2011ecs40 fall Memory Cell Layout main Scan_address Scanf malloc/free a.out

10/07/2011ecs40 fall malloc/free a.out 71 setCourseName GradeBook getCourseName displayMessage string Course name C++

10/07/2011ecs40 fall setCourseName GradeBook getCourseName displayMessage string Course name Java

10/07/2011ecs40 fall

10/07/2011ecs40 fall

09/23/2011ecs150 Fall Applications…….. Hardware: CPU/Memory/HD/DVD/Wireless… OS ….where applications meet Hardware!!!

10/18/2011ecs40 fall

09/23/2011ecs150 Fall

09/23/2011ecs150 Fall Kernel and User Space FOO Process FOO Memory space for this process System call (or trap into the kernel) program System Call conceptually Kernel Resources (disk or IO devices) FOO Process FOO in the Kernel

09/23/2011ecs150 Fall FreeBSD Kernel: Services l Timer/clock, descriptor, process l Memory Management: paging/swapping l I/O control and terminal l File System l Inter-process communication l Networking

10/07/2011ecs40 fall malloc/free a.out 80 setCourseName GradeBook getCourseName displayMessage string Course name C++

81 Define a Class Hierarchy l Syntax: class DerivedClassName : access-level BaseClassName where –access-level specifies the type of derivation l private by default, or l public l Any class can serve as a base class –Thus a derived class can also be a base class

82 class Time Specification class Time{ public : void Set ( int h, int m, int s ) ; void Increment ( ) ; void Write ( ) const ; Time ( int initH, int initM, int initS ) ; // constructor Time ( ) ; // default constructor protected : int hrs ; int mins ; int secs ; } ; // SPECIFICATION FILE ( time.h)

l Time l MyTime l YourTime 10/18/2011ecs40 fall

84 Class Interface Diagram Protected data: hrs mins secs Set Increment Write Time Time class

85 Derived Class ExtTime // 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 and use public inheritance { public : void Set ( int h, int m, int s, ZoneType timeZone ) ; void Write ( ) const; //overridden ExtTime (int initH, int initM, int initS, ZoneType initZone ) ; ExtTime (); // default constructor private : ZoneType zone ; // added data member } ;

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

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

l Inheritance –Class CwD: public Time l Composite Object –Class CwD { … public: Time time; …. } 10/18/2011ecs40 fall

89 Implementation of ExtTime Default Constructor ExtTime :: ExtTime ( ) { zone = EST ; } The default constructor of base class, Time(), is automatically called, when an ExtTime object is created. ExtTime et1; hrs = 0 mins = 0 secs = 0 zone = EST et1

90 Implementation of ExtTime Another Constructor ExtTime :: ExtTime (int initH, int initM, int initS, ZoneType initZone) : Time (initH, initM, initS) // constructor initializer { zone = initZone ; } ExtTime *et2 = new ExtTime(8,30,0,EST); hrs = 8 mins = 30 secs = 0 zone = EST et ???

91 Implementation of ExtTime void ExtTime :: Set (int h, int m, int s, ZoneType timeZone) { Time :: Set (hours, minutes, seconds); // same name function call zone = timeZone ; } void ExtTime :: Write ( ) const // function overriding { string zoneString[8] = { “ EST ”, “ CST ”, MST ”, “ PST ”, “ EDT ”, “ CDT ”, “ MDT ”, “ PDT ” } ; Time :: Write ( ) ; cout << ‘ ‘ <<zoneString[zone]<<endl; }

92 Working with ExtTime #include “ exttime.h ” … int main() { ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; // default constructor called thatTime.Write( ) ; // outputs 00:00:00 EST thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDT thisTime.Increment ( ) ; thisTime.Write ( ) ; // outputs 08:35:02 PST }

l TimeTime l MyTime ItsTime l YourTime 10/18/2011ecs40 fall

l PhonePhone l iPhone5 Android l Ecs40_Phone 10/18/2011ecs40 fall

95 Dynamic Binding in OOP Time print() Classes MyTime/ItsTime print() YourTime print() inherits (isa) X x; Y y; Z z; X *px; px = & ??; // can be x,y,or z px->print(); // ??

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

97 Polymorphism – An Introduction l Definition –noun, the quality or state of being able to assume different forms - Webster l An essential feature of an OO Language l It builds upon Inheritance l Allows run-time interpretation of object type for a given class hierarchy –Also Known as “Late Binding” l Implemented in C++ using virtual functions

98 Dynamic Binding l Is the run-time determination of which function to call for a particular object of a derived 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 l Dynamic binding requires pass-by-reference

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

This is the way we like to see… void Print (Time * someTime ) { cout << “Time is “ ; someTime->Write ( ) ; cout << endl ; } CLIENT CODE Time startTime( 8, 30, 0 ) ; ExtTime endTime(10, 45, 0, CST) ; Time *timeptr; timeptr = &startTime; Print ( timeptr ) ; timeptr = &endTime; Print ( timeptr ) ; OUTPUT Time is 08:30:00 Time is 10:45:00 CST Time::write() ExtTime::write()

101 Virtual Functions l Virtual Functions overcome the problem of run time object determination l Keyword virtual instructs the compiler to use late binding and delay the object interpretation l How ? –Define a virtual function in the base class. The word virtual appears only in the base class –If a base class declares a virtual function, it must implement that function, even if the body is empty –Virtual function in base class stays virtual in all the derived classes –It can be overridden in the derived classes –But, a derived class is not required to re-implement a virtual function. If it does not, the base class version is used

10/18/2011ecs40 fall

10/18/2011ecs40 fall l PhonePhone l iPhone5 Android l Ecs40_Phone

10/18/2011ecs40 fall l PhonePhone l iPhone5 Android l Ecs40_Phone

105 Dynamic Binding l Is the run-time determination of which function to call for a particular object of a derived class based on the type of the argument –At the moment of calling “constructor”! l Declaring a member function to be virtual instructs the compiler to generate code that guarantees dynamic binding l Dynamic binding requires pass-by-reference

What should be the return value? int Func_Foo(X, Y) { int S = 1; S = X + Y; return X+Y; } 10/18/2011ecs40 fall

What should be the return value? int Func_Foo(X, Y) { int S = 1; S = X + Y; return X+Y; } 10/18/2011ecs40 fall int S = 3; printf(“%d\n”, Func_Foo(S+2, S+3);

What should be the return value? int Func_Foo(S+2, S+3) { int S = 1; S = (S+2) + (S+3); return (S+2)+(S+3); } 10/18/2011ecs40 fall int S = 3; printf(“%d\n”, Func_Foo(S+2, S+3);

10/18/2011ecs40 fall Substitute argument for parameter at each occurrence of parameter: Invocation: P(A, B+2, 27+3) Definition: procedure P(X,Y,Z) {int I; I=7; X = I + (7/Y)*Z;} Meaning: P(X,Y,Z) {int I; I=7; A=I+(7/(B+2))*(27+3);}

Templates (Ch.14) l Name substitution l Type substitutions –Functions –Classes 10/18/2011ecs40 fall

10/18/2011ecs40 fall l Function templates and class templates enable you to specify, with a single code segment, an entire range of related (overloaded) functions—called function-template specializations—or an entire range of related classes—called class-template specializations. l This technique is called generic programming. l Note the distinction between templates and template specializations: –Function templates and class templates are like stencils out of which we trace shapes. –Function-template specializations and class-template specializations are like the separate trac-ings that all have the same shape, but could, for example, be drawn in different colors. l In this chapter, we present a function template and a class tem- plate.

10/18/2011ecs40 fall All function-template definitions begin with keyword template followed by a list of template parameters to the function template enclosed in angle brackets ( ); each template parameter that represents a type must be preceded by either of the interchangeable keywords class or typename, as in l template –Or l template –Or l template l The type template parameters of a function-template definition are used to specify the types of the arguments to the function, to specify the return type of the function and to declare variables within the function. Keywords typename and class used to specify function-template parameters actually mean “any fundamental type or user-defined type.”

10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall A critical difference between Virtual Functions and Templates…

10/18/2011ecs40 fall When the compiler detects a printArray function invocation in the client program (e.g., lines 29 and 34), the compiler uses its overload resolution capabilities to find a definition of function printArray that best matches the function call. In this case, the only printArray function with the appropriate number of parameters is the printArray function template (lines 7– 14). l Consider the function call at line 29. The compiler compares the type of printArray ’s first argument ( int * at line 29) to the printArray function template’s first parameter ( const T * const at line 8) and deduces that replacing the type parameter T with int would make the argument consistent with the parameter. Then, the compiler substitutes int for T throughout the template definition and compiles a printArray specialization that can display an array of int values.

10/18/2011ecs40 fall The function-template specialization for type int is void printArray( const int * const array, int count ) { for ( int i = 0; i < count; i++ ) cout << array[ i ] << " " ; cout << endl; } // end function printArray l As with function parameters, the names of template parameters must be unique inside a template definition. l Template parameter names need not be unique across different function templates. Figure 14.1 demonstrates function template printArray. It’s important to note that if T (line 7) represents a user-defined type (which it does not in Fig. 14.1), there must be an overloaded stream insertion operator for that type; otherwise, the first stream insertion operator in line 11 will not compile.

10/18/2011ecs40 fall

10/18/2011ecs40 fall

Call by Name l Substitutions essentially 10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall When shall we use Templates?

10/18/2011ecs40 fall When shall we use Templates? HW#5?

10/18/2011ecs40 fall

10/18/2011ecs40 fall

10/18/2011ecs40 fall