Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "10/18/2011ecs40 fall 20121 Software Development & Object- Oriented Programming ecs40 Fall 2012: Software Development & Object- Oriented Programming #02:"— Presentation transcript:

1 10/18/2011ecs40 fall 20121 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 http://www.cs.ucdavis.edu/~wu/ wu@cs.ucdavis.edu

2 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

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

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

5 ©1992-2012 by Pearson Education, Inc. All Rights Reserved.

6

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

8 ©1992-2012 by Pearson Education, Inc. All Rights Reserved.

9

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

11 ©1992-2012 by Pearson Education, Inc. All Rights Reserved.

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

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

14 ©1992-2012 by Pearson Education, Inc. All Rights Reserved.

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

16 ©1992-2012 by Pearson Education, Inc. All Rights Reserved.

17

18

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

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

21 10/18/2011ecs40 fall 201221 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.

22 10/18/2011ecs40 fall 201222 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.

23 10/18/2011ecs40 fall 201223 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.

24 10/18/2011ecs40 fall 201224

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

26 10/18/2011ecs40 fall 201226 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.

27 10/18/2011ecs40 fall 201227 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.

28 10/18/2011ecs40 fall 201228

29 ©1992-2012 by Pearson Education, Inc. All Rights Reserved.

30

31

32

33

34

35

36

37

38

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

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

41 10/18/2011ecs40 fall 201241

42 10/18/2011ecs40 fall 201242

43 10/18/2011ecs40 fall 201243

44 10/18/2011ecs40 fall 201244

45 10/18/2011ecs40 fall 201245

46 10/18/2011ecs40 fall 201246

47 10/18/2011ecs40 fall 201247

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

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

50 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 201250

51 10/18/2011ecs40 fall 201251

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

53 10/18/2011 Base Constructor ecs40 fall 201253

54 10/18/2011 Base Constructor ecs40 fall 201254 Derived Constructor

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

56 10/18/2011ecs40 fall 201256

57 10/18/2011 Base Constructor ecs40 fall 201257 Derived Constructor

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

59 10/18/2011 Base Constructor ecs40 fall 201259 Derived Constructor

60 10/18/2011 Base Constructor ecs40 fall 201260 Derived Constructor

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

62 10/18/2011ecs40 fall 201262

63 10/18/2011ecs40 fall 201263

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

65 10/18/2011ecs40 fall 201265

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

67 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 201267

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

69 09/23/2011ecs150 Fall 201169

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

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

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

73 10/07/2011ecs40 fall 201273

74 10/07/2011ecs40 fall 201274

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

76 10/18/2011ecs40 fall 201276

77 09/23/2011ecs150 Fall 201177

78 09/23/2011ecs150 Fall 201178 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

79 09/23/2011ecs150 Fall 201179 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

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

81 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 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)

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

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

85 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 86 Class Interface Diagram Protected data: hrs mins secs ExtTime class Set Increment Write Time Set Increment Write ExtTime Private data: zone

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

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

89 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 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 et2 5000 ??? 6000 5000

91 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 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 }

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

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

95 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(); // ??

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

97 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 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 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 ; } ;

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

102 10/18/2011ecs40 fall 2012102

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

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

105 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

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

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

108 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 2012108 int S = 3; printf(“%d\n”, Func_Foo(S+2, S+3);

109 10/18/2011ecs40 fall 2012109 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);}

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

111 10/18/2011ecs40 fall 2012111 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.

112 10/18/2011ecs40 fall 2012112 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.”

113 10/18/2011ecs40 fall 2012113

114 10/18/2011ecs40 fall 2012114

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

116 10/18/2011ecs40 fall 2012116 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.

117 10/18/2011ecs40 fall 2012117 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.

118 10/18/2011ecs40 fall 2012118

119 10/18/2011ecs40 fall 2012119

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

121 10/18/2011ecs40 fall 2012121

122 10/18/2011ecs40 fall 2012122

123 10/18/2011ecs40 fall 2012123

124 10/18/2011ecs40 fall 2012124

125 10/18/2011ecs40 fall 2012125

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

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

128 10/18/2011ecs40 fall 2012128

129 10/18/2011ecs40 fall 2012129

130 10/18/2011ecs40 fall 2012130


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

Similar presentations


Ads by Google